Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

function - Mode in R by groups

I need to calculate the mode of an identity number for each group of ages. Let's suposse 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 ge tthe following error:

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

Don't know what the problem is.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...