2
I need to calculate the MODA of online values in a data.frame. As in R
there is no function already set for FASHION, I used a custom function:
moda = function(x) {
z = table(as.vector(x))
names(z)[z == max(z)]
}
teste1 = moda(c(1,2,3,4,5,5,5))
print(teste1)
[1] 5
The function moda
works very well by the way, now let’s go to another case:
teste2 = moda(c(1,1,1,2,3,4,5,5,5))
print(teste2)
[1] "1" "5"
In teste2, the vector has bimodal value and the function moda
displays two values. Now let’s go to the third case using a data.frame:
print(DADOS)
Linha A B C D E
L1 4 3 2 1 4
L2 1 11 1 1 1
L3 0 1 2 2 4
L4 2 0 0 8 0
In this case I will have to create another column with values of each line calculated by MODA:
DADOS = DADOS %>%
rowwise() %>%
mutate(MODA = moda(c(A,B,C,D,E)))
print(DADOS)
Linha A B C D E MODA
L1 4 3 2 1 4 4
L2 1 11 1 1 1 1
L3 0 1 2 2 4 2
L4 2 0 0 8 0 0
It worked perfectly, but we arrived at the "problem situation". In the latter case I will use a different data.frame:
print(DADOS_2)
Linha A B C D E
L1 4 3 2 2 4
L2 1 11 1 1 1
L3 0 1 2 3 4
L4 2 0 0 8 0
As in the previous case I will have to create another column with values of each line calculated by MODA:
DADOS_2 = DADOS_2 %>%
rowwise() %>%
mutate(MODA = moda(c(A,B,C,D,E)))
print(DADOS_2)
Error: Column `MODA` must be length 1 (the group size), not 2
The R
displays me the error message, because on the basis DADOS_2
the line L1
brings a clear example of bimodal L1 value=(4,3,2,2,4). And because it is a bimodal value, the R
cannot assign two values in a single column.
What should I do in this case? How can I calculate MODA in line with bimodal value in a date.frame?
Thanks for the answer, I’ll test.
– Izak Mandrak
Giovani used his solution with my base which has six columns. But sent me an error message: Warning message:Expected 3 Pieces.
– Izak Mandrak
When it went down to three columns it worked, but with 6 columns I get this error message. In your code is how to define the column numbers I want to work?
– Izak Mandrak
Try increasing the number of columns. Put 6 (for example,
mode_1
,mode_2
untilmode_6
. Do it within the argumentinto = c()
and inmutate_at
.– neves
For example: have how I choose the columns (A,C and E) to calculate the FASHION?
– Izak Mandrak
Just give a
select
and choose these variables at the beginning of the analysis.– neves
One last thing Giovani... when I have a sample example: c(1,2,3,4,5,6) he considers all as fashion, but in fact there is no fashion because no number is repeated.
– Izak Mandrak
Then you would have to adjust the function to solve this detail. See that the fashions were created based on the function
moda
.– neves