R mode by group

I need to calculate the ID mode for each age group. Denote the following table:

library(data.table)
DT = data.table(age=c(12,12,3,3,12),v=rnorm(5), number=c("122","125","5","5","122"))

So, I created a function:

g <- function(number) {
      ux <- unique(number)
      ux[which.max(tabulate(match(number, ux)))]
    }
H<-function(tabla){data.frame(MODA=g, count=nrow(tabla))}
clasif_edad1<-ddply(DF,.(age), H)
View(clasif_edad1)

But I am wrong:

Error: arguments imply differing number of rows: 0, 1

The output should be:

age      v    number moda
12  0,631152199 122 122
12  0,736648714 125 122
3   0,545921527 5   5
3   0,59336284  5   5
12  0,836685437 122 122

I don’t know what the problem is.

thank

+2
source share
3 answers

One approach:

> myfun <- function(x) unique(x)[which.max(table(x))]
> DT[ , moda := myfun(number), by = age]
> DT
   age          v number moda
1:  12 -0.9740026    122  122
2:  12  0.6893727    125  122
3:   3 -0.9558391      5    5
4:   3 -1.2317071      5    5
5:  12 -0.9568919    122  122
+2
source

You can use dplyrfor this:

library(dplyr)
modes_by_age <- summarise(group_by(DT, age), group_mode = g(number))
inner_join(DT, modes_by_age)

This gives the desired result:

Source: local data table [5 x 4]

  age         v number group_mode
1   3 0.5524352      5          5
2   3 0.2869912      5          5
3  12 0.8987475    122        122
4  12 0.9740715    125        122
5  12 2.5058450    122        122
0
source

R-. , :

merge(DT, setNames(aggregate(number~age, data=DT, g), c("age", "moda")), by="age")
#    age          v number moda
# 1:   3  1.7148357      5    5
# 2:   3  0.9504811      5    5
# 3:  12 -0.7648237    122  122
# 4:  12  0.9011115    125  122
# 5:  12 -0.8718779    122  122

, , , DT - .

0

All Articles