【发布时间】:2021-11-26 07:18:11
【问题描述】:
可能是一个基本问题。
我有一个key - valuedata.frame(下面是df):
features <- paste0("f",1:5)
set.seed(1)
ids <- paste0("id",1:10)
df <- do.call(rbind,lapply(ids,function(i){
data.frame(id = i, feature = sample(features,3,replace = F))
}))
我想tidyr::spread 或reshape2::dcast 它,所以行是id' the columns are feature, but the values are the sum of featuresfor eachid`。
一个简单的:
reshape2::dcast(df, id ~ feature)
没有做到这一点。它只是用features 和NAs 填写
将fun.aggregate = sum 添加到上述命令会导致错误:
> reshape2::dcast(df, id ~ feature, fun.aggregate = sum)
Using feature as value column: use value.var to override.
Error in .fun(.value[0], ...) : invalid 'type' (character) of argument
而且 tidyr::spread 也会导致错误:
tidyr::spread(df, key = id, value = feature)
Error: Each row of output must be identified by a unique combination of keys.
Keys are shared for 30 rows:
有什么想法吗?
【问题讨论】:
标签: r tidyr reshape2 spread dcast