我想添加新闻栏目的每组在类型的计数。我的数据帧是这样的:
# color type
# black chair
# black chair
# black sofa
# pink plate
# pink chair
# red sofa
# red plate 我正在寻找类似这样的东西:
# color chair sofa plate
# black 2 1 0
# pink 1 0 1
# red 0 1 1我使用了table(df$color, df$type),但是结果没有列'color‘的名称
发布于 2021-10-08 05:57:36
我们可以使用来自base R的table
table(df)或使用pivot_wider
library(tidyr)
pivot_wider(df, names_from = type, values_from = type,
values_fn = length, values_fill = 0)
# A tibble: 3 × 4
color chair sofa plate
<chr> <int> <int> <int>
1 black 2 1 0
2 pink 1 0 1
3 red 0 1 1或使用dcast
library(data.table)
dcast(setDT(df), color ~ type, value.var = 'type', length, fill = 0)数据
df <- structure(list(color = c("black", "black", "black", "pink", "pink",
"red", "red"), type = c("chair", "chair", "sofa", "plate", "chair",
"sofa", "plate")), class = "data.frame", row.names = c(NA, -7L
))https://stackoverflow.com/questions/69491122
复制相似问题