我想获取数据框的唯一行,然后将其与另一行属性连接。然后我希望能够计算出品种的数量,例如特定类型或来源的独特水果的数量。
第一个数据框有我的水果清单:
fruits <- read.table(header=TRUE, text="shop fruit
1 apple
2 orange
3 apple
4 pear
2 banana
1 banana
1 orange
3 banana")
第二个数据框有我的属性:
fruit_class <- read.table(header=TRUE, text="fruit type origin
apple pome asia
banana berry asia
orange citrus asia
pear pome newguinea")
这是我对这个问题的笨拙解决方案:
fruit <- as.data.frame(unique(fruit[,2])) #get a list of unique fruits
colnames(fruit)[1] <- "fruit" #this won't rename the column and I don't know why...
fruit_summary <- join(fruits, fruit_class, by="fruit" #create a data frame that I can query
count(fruit_summary, "origin") #for eg, summarise the number of fruits of each origin
所以我的主要问题是:如何更优雅地表达这一点(即单行而不是 3 行)?其次:为什么它不允许我重命名列?
提前致谢