我们可以用 melt/dcast
library(reshape2) dcast(melt(df1, id.var='message.id'), value~variable, value.var='message.id', length)
或者使用包装器 recast
recast(df1, id.var='message.id', value~variable, length) # value sender recipient #1 A 3 0 #2 B 3 2 #3 C 0 2 #4 D 0 1 #5 Q 0 1
如果我们需要使用 dplyr/tidyr
library(dplyr) library(tidyr) gather(df1, messages, address, 2:3) %>% group_by(messages, address) %>% summarise(n=n()) %>% spread(messages, n, fill=0) # address sender recipient # (chr) (dbl) (dbl) #1 A 3 0 #2 B 3 2 #3 C 0 2 #4 D 0 1 #5 Q 0 1