I have two data frames, df1 and df2 (see below). From df1 I want to write the value of letter
into the relevant column in df2, such e.g. that the value group.x
for ID=1
is C and group.y
is B (from df1). As I don't really know where to start looking for answers, some help in pointing me in the right direction for solving this would be greatly appreciated...
> no.pers <- 3
> df1 <- data.frame(
+ ID = rep(1:no.pers, each = 3),
+ letter = sample(LETTERS[1:3],
+ no.pers*3,
+ replace = TRUE),
+ group = rep(letters[seq(24,26)],
+ no.pers,
+ replace = TRUE)
+ )
> df1
ID letter group
1 1 C x
2 1 B y
3 1 C z
4 2 C x
5 2 B y
6 2 B z
7 3 B x
8 3 C y
9 3 B z
> df2 <- data.frame(ID = unique(df1$ID),
+ setNames(
+ replicate(length(unique(df1$group)),
+ 0,
+ simplify = FALSE),
+ paste0("group.",unique(df1$group)))
+ )
> df2
ID group.x group.y group.z
1 1 0 0 0
2 2 0 0 0
3 3 0 0 0