Merging rows of binary data based on columns using ddply [duplicate]

你。 提交于 2019-12-24 07:09:37

问题


I have the following dataframe for which I want merge together binary values from an amount of rows.

df =data.frame(ID=c(rep("A",5),rep("B",5)), nr=c(rep("2",5),rep("3",5)), replicate(10,sample(0:1,10,rep=TRUE)))

eg:

# ID nr X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# A  2  0  0  1  1  1  1  1  1  1   0
# A  2  1  0  0  0  0  0  0  1  0   1
# A  2  0  0  1  1  1  0  0  0  0   1
# A  2  0  0  0  0  0  1  1  1  0   1
# A  2  0  0  0  1  0  1  1  0  1   1
# B  3  0  1  0  0  1  0  0  0  1   1
# B  3  1  1  0  0  0  0  0  0  0   1
# B  3  1  0  1  0  0  0  1  1  0   1
# B  3  1  1  1  0  1  0  0  1  1   1
# B  3  0  0  0  1  0  0  0  1  0   1

Now I want to merge rows for the first 2 columns in this case:

df2 = ddply(df, c(1:2), summarise, numcolwise(sum,c(3:12)))

But I get the following error:

Error in vector(type, length) : 
   vector: cannot make a vector of mode 'closure'.

Also I would want that anything higher than 1 to be reset to 1 to keep it binary, but since I couldn't get past the error I haven't tried it yet.

I know variations of this question have been asked before but I haven't found it like this before. Keep in mind that I want to use column indices because I'm working with large data.


回答1:


If your data is quite large (as mentioned in comments), forget about plyr, try data.table

library(data.table)
setDT(df)[, lapply(.SD, sum), by = list(ID, nr)]

##    ID nr X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
## 1:  A  2  2  3  5  2  5  2  1  3  4   1
## 2:  B  3  3  3  4  1  3  2  3  2  1   4

Or if you want to stick with the plyr family, move on to the next generation: dplyr

library(dplyr)
df %>%
  group_by(ID, nr) %>%
  summarise_each(funs(sum))

# Source: local data table [2 x 12]
# Groups: ID
# 
#   ID nr X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# 1  A  2  2  3  5  2  5  2  1  3  4   1
# 2  B  3  3  3  4  1  3  2  3  2  1   4


来源:https://stackoverflow.com/questions/25644512/merging-rows-of-binary-data-based-on-columns-using-ddply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!