r - 传播或 dcast 并填写计数
问题描述
大概是个基本问题。
我有一个key - value
data.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
特征, but the values are the sum of
特征for each
id`。
一个简单的:
reshape2::dcast(df, id ~ feature)
达不到这一点。它只是用feature
s 和NA
s填充
添加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:
任何的想法?
解决方案
我认为您想计算功能而不是sum
它们。试试这个功能length
。
tidyr::pivot_wider(df, names_from = feature,
values_from = feature, values_fn = length, values_fill = 0)
或与dcast
.
library(data.table)
dcast(setDT(df), id~feature, value.var = 'feature', fun.aggregate = length)
在基础 R 中, usingtable(df)
将给出相同的输出。
table(df)
# feature
#id f1 f2 f3 f4 f5
# id1 1 0 1 1 0
# id10 1 0 1 1 0
# id2 1 1 0 0 1
# id3 0 1 1 1 0
# id4 1 0 1 0 1
# id5 1 1 0 0 1
# id6 1 1 1 0 0
# id7 1 0 0 1 1
# id8 1 1 0 0 1
# id9 0 1 0 1 1
推荐阅读
- javascript - 使用 jest、rtl 和 ionic 对输入文本的状态更新测试反应功能
- graphql - 如何在 graphql-express 中放置一个单独的解析器对象?
- ruby-on-rails - Rails 中的多对多关联
- git - 如何查看文件是否包含在项目文件中?
- html - 17列的引导表问题,没有响应
- python - How to sum specific columns while keeping the unique ID without nan
- r - 如何将“YYYY-mm-dd”日期数据类型更改为 UTC Posixct 数据类型?
- json - 当给定“应用程序/json”的标头时,JS Fetch 返回 HTML
- javascript - 如何在 golang 中获取 javascript 网站内容
- c - Windows PE 格式资源传输问题