R按模式分组 [英] Mode in R by groups
本文介绍了R按模式分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
library(data.table)
DT = data.table(age = c( 12,12,3,3,12),v = rnorm(5),number = c(122,125,5,5,122))
$所以我创建了一个函数:
<$ c $
$ b $ (b)(b)(b)(b)(b)(b)(b)(b) b $ b H <-function(tabla){data.frame(MODA = g,count = nrow(tabla))}
clasif_edad1 <-ddply(DF,。(age),H)
View (clasif_edad1)
但是我发现以下错误:
$ b $ $
b输出应该是:
pre $ code年龄v数字模式
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
不知道问题所在。
谢谢
解决方案
一种方法:
> myfun< - function(x)unique(x)[which.max(table(x))]
> DT [,moda:= myfun(number),by = age]
> DT
年龄v数字模式
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
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
解决方案
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
这篇关于R按模式分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文