我有以下数据框;基于具有因子的列值的行总和
Fruit <- c("orange", "orange", "apple", "pineapple", "lemon", "apple", "orange")
Name <- c("julius", "julius", "john", "mary", "kathy", "john", "julius")
df <- data.frame(Fruit, Name);df
我的目标是让每个人吃的所有水果数量总和,以便最后得到下面的表格;
orange apple pineapple lemon
julius 2 1
john 2
mary 1
kathy 1 1
我在试用聚合函数,但只能设法让它输出每个人吃的水果总数如下;
df2 <- aggregate(Fruit~Name,df,length); df2
输出是;
Name Fruit
1 john 2
2 julius 3
3 kathy 1
4 mary 1
任何帮助将不胜感激。由于
感谢@Codoremifa。你做得这么简单。我使用第二个选项,虽然自第一次抛出以下错误“package'dcast'不可用(对于R版本3.0.2)” – kigode
'table(df)'在这种情况下工作,因为您没有任何其他变量在数据框中。作为一般情况,'with(df,table(Fruit,Name))'更好。 – lebatsnok
谢谢@lebatsnok。 – TheComeOnMan