I have 2 data frames:
df1:
a
s1
s2
s3
s4
df2:
a b
s1 w
s1 x
s4 y
s2 z
s4 x
I want to append to df1 as many columns as unique values are in df2$b (w, x, y, z), and for each df1$a and new column add a 1 if df2$a has a row associating them. This is cumbersome to explain, maybe showing the desired output is better:
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
I have tried
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))
}
But this does not work, and I guess the problem lies in the
a == df1$a
bit, but I do not know which is the proper syntaxis for this. Any help is appreciated!