【发布时间】:2017-08-15 02:52:48
【问题描述】:
我正在尝试根据多列查找数据框的最小值。我可以使用下面的聚合函数成功地做到这一点。但是,结果不包含输入数据框中没有数据的因素组合。
我有什么:
# all possibilities of fruits, cities, and vegetables:
fruits<-c('apple','banana','grape')
cities<-c('new york','chicago','los angeles')
vegetables<-c('cucumber','mushroom')
#my input (ie, a sample from a test:
inputdf<-data.frame(fruit=c('apple','apple','apple','banana','banana','banana','grape','grape','grape'),city=c('new york','new york','new york','new york','chicago','los angeles','chicago','chicago','chicago'),vegetable=c('cucumber','cucumber','mushroom','cucumber','mushroom','mushroom','cucumber','cucumber','cucumber'),value=c(5,3,4,6,5,7,2,7,4))
#my aggregation:
outdf<-aggregate(value ~ fruit + city + vegetable,inputdf,function(x) min(x))
我得到的输出是:
fruit city vegetable value
grape chicago cucumber 2
apple new york cucumber 3
banana new york cucumber 6
banana chicago mushroom 5
banana los angeles mushroom 7
apple new york mushroom 4
这是正确的,但是,我还想要与输入 df 中根本不存在的列组合相对应的行:
fruit city vegetable value
apple new york cucumber 3
apple new york mushroom 4
apple chicago cucumber NA
apple chicago mushroom NA
apple los angeles cucumber NA
apple los angeles mushroom NA
banana new york cucumber 6
banana new york mushroom NA
banana chicago cucumber NA
banana chicago mushroom 5
banana los angeles cucumber NA
banana los angeles mushroom 7
grape new york cucumber NA
grape new york mushroom NA
grape chicago cucumber 2
grape chicago mushroom NA
grape los angeles cucumber NA
grape los angeles mushroom NA
我希望能够对要组合的任意数量的列执行此操作。有没有一种简单的方法可以做到这一点?我想要该输出的原因是因为我需要将 NA 转换为特定值并再次在相同子集上平均这些值。谢谢!
【问题讨论】:
标签: r