根据R中的三列计算频率

根据R中的三列计算频率,r,frequency,R,Frequency,这是我的数据框 id ingredient1 ingredient2 ingredient3 1 apple milk cheese 5 pear apple 3 lettuces tomato salt 12 ribs tomato salt 20 cheese

这是我的数据框

id    ingredient1    ingredient2    ingredient3
1      apple            milk           cheese
5      pear             apple          
3      lettuces         tomato         salt
12     ribs             tomato         salt
20     cheese           milk           tomato
... ...
这里有200多行 我知道如何通过表格获得频率。但是在这里,我真的不知道怎么做。 这是我想要的理想输出:

var     freq
apple     2
milk      2
cheese    2
pear      1
lettuces  1
tomato    3
salt      2
ribs      1
... ... 

假设您需要所有“成分”列的总频率,我们通过删除第一列(
df1[-1]
)对数据集进行子集,然后
取消列出
以生成一个
向量
,并使用
获得唯一元素的频率。如果您需要
data.frame
输出,我们可以使用
as.data.frame
将其包装起来

res <- as.data.frame(table(unlist(df1[-1])))
你可以试试:

library(dplyr)
library(tidyr)

df %>% 
  gather(key, value, -id) %>% 
  group_by(ingredient = value) %>% 
  tally()
其中:

#Source: local data frame [9 x 2]
#
#  ingredient n
#1      apple 2
#2     cheese 2
#3   lettuces 1
#4       milk 2
#5       pear 1
#6       ribs 1
#7       salt 2
#8     tomato 3
#9         NA 1

我的本能是
melt
这个,但是如果
data.frame
实际上只有4个columns@MichaelChirico是
melt
是另一个不错的选择。但是,我想保留所有的
基本R
函数。您可以转换为
数据.table
melt
,然后使用其中一列,我们得到
.N
。您也可以这样做:
df%>%gather(key,value,-id)%%>%groupby(component=value)%%>%tally()
@stevenbaupré您可以将其作为一种替代方法发布。用
理货看起来不错
两种解决方案都很有用。但我不能两者都接受。对不起!真的谢谢你!
#Source: local data frame [9 x 2]
#
#  ingredient n
#1      apple 2
#2     cheese 2
#3   lettuces 1
#4       milk 2
#5       pear 1
#6       ribs 1
#7       salt 2
#8     tomato 3
#9         NA 1