与data.table:
library(data.table)
dcast(setDT(df), id ~ color, fun.aggregate = length)
# id blue red yellow
# 1: 001 1 1 1
# 2: 002 1 0 0
# 3: 003 1 0 1
与tidyr的逻辑相同:
library(tidyr)
pivot_wider(df, names_from=color, values_from=color, values_fn=length, values_fill=0)
# id blue yellow red
# <chr> <int> <int> <int>
# 1 001 1 1 1
# 2 002 1 0 0
# 3 003 1 1 0
Base R:
out <- as.data.frame.matrix(pmin(with(df, table(id, color)), 1))
out$id <- rownames(out)
out
# blue red yellow id
# 001 1 1 1 001
# 002 1 0 0 002
# 003 1 0 1 003
可重复的数据
df <- data.frame(
id = c("001", "001", "001", "002", "003", "003"),
color = c("blue", "yellow", "red", "blue", "blue", "yellow")
)