具有ddply功能的频率表

时间:2016-01-08 21:56:42

标签: r algorithm

ID<-c("R1","R2","R2","R3","R3","R4","R4","R4","R4","R3","R3","R3","R3","R2","R2","R2","R5","R6")
event<-c("a","b","b","M","s","f","y","b","a","a","a","a","s","c","c","b","m","a")
df<-data.frame(ID,event)

如何修改以下代码以获取此表。 2 - 如何获得每个频率元素的频率平均值?例如:a的频率平均值为1 + 3 + 1 + 1/4。

ddply(df,.(ID),summarise,N=sum(!is.na(ID)),frequency=length(event))

ID  N   Number-event-level  levels       frequency
R1  1      1                 a             a=1
R2  5      2                 b,c         b=3,c=2
R3  6      3                 M,a,s       M=1,a=3,s=2
R4  4      4                 f,y,b,a    f=1,y=1,b=1,a=1
R5  1      1                 m             m=1
R6  1      1                 a             a=1 

1 个答案:

答案 0 :(得分:3)

以下是第一个问题的答案:

ddply(df,.(ID),summarise,
      N=length(event),
      Number.event.level=length(unique(event)),
      levels=paste(sort(unique(event)),collapse=","),
      frequency=paste(paste(sort(unique(event)),table(event)[table(event)>0],sep="="),collapse=","))
#   ID N Number.event.level  levels       frequency
# 1 R1 1                  1       a             a=1
# 2 R2 5                  2     b,c         b=3,c=2
# 3 R3 6                  3   a,M,s     a=3,M=1,s=2
# 4 R4 4                  4 a,b,f,y a=1,b=1,f=1,y=1
# 5 R5 1                  1       m             m=1
# 6 R6 1                  1       a             a=1

对于你的第二个问题,似乎你想在频率大于0时获得平均频率。如果是这样的话,你可以这样做:

apply(table(df),2,function(x) mean(x[x>0]))
#   a   b   c   f   m   M   s   y 
# 1.5 2.0 2.0 1.0 1.0 1.0 2.0 1.0 

<强>更新

如果您想为第三个变量的每个级别执行最后一个部分,并且仍想使用ddply(),则可以执行以下操作:

df1 <- rbind(df,df)
df1$cat <- rep(c("a","b"),each=nrow(df))

ddply(df1,.(cat),function(y) apply(table(y),2,function(x) mean(x[x>0])))
#   cat   a b c f m M s y
# 1   a 1.5 2 2 1 1 1 2 1
# 2   b 1.5 2 2 1 1 1 2 1