【发布时间】:2021-03-13 21:27:38
【问题描述】:
我有 2 个数据框:
df1:
a
s1
s2
s3
s4
df2:
a b
s1 w
s1 x
s4 y
s2 z
s4 x
我想将与 df2$b (w, x, y, z) 中的唯一值一样多的列附加到 df1,如果 df2$a 有一行关联,则为每个 df1$a 和新列添加 1他们。这解释起来很麻烦,也许显示所需的输出更好:
a w x y z
s1 1 1 0 0
s2 0 0 0 1
s3 0 0 0 0
s4 0 1 1 0
我试过了
for (col_name in unique(df2$b)){
df1 %<>%
mutate(!!as.character(col_name) := ifelse(col_name %in% filter(df2,
a == df1$a)$b,
yes = 1,
no = 0))
}
但这不起作用,我猜问题出在
a == df1$a
bit,但我不知道哪个是正确的语法。任何帮助表示赞赏!
【问题讨论】:
-
你可以使用
table(df2)