0

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
avriis
  • 1,581
  • 4
  • 17
  • 31
  • 1
    Can't you just work with `df1` while ignoring `df2` completely? something like `reshape2::dcast(df1, ID ~ group, value.var = "letter")`? – David Arenburg Jan 05 '16 at 13:08
  • Works brilliantly, thanks! If you want to make it into an answer, I can accept it as answered... – avriis Jan 05 '16 at 13:12
  • 1
    This was answered many times on SO, as this is a very common data manipulation procedure. See the dupe. It has many other possibilities too. – David Arenburg Jan 05 '16 at 13:15
  • @DavidArenburg Alright, I am deleting the answer if you are so particular about the dupe thing. The fact is that the OP have enough time to google before posting a question. If he/she doesn't do that, why should I google for a potential dupe. It's just a waste of my time. – akrun Jan 05 '16 at 13:42
  • @akrun OP isn't familiar with R/R terminology enough to know how to Google such thing in the first place. – David Arenburg Jan 05 '16 at 13:47
  • @DavidArenburg In my workplace, most of the sites are blocked. Also, I dont think I should be doing the google for them. – akrun Jan 05 '16 at 13:48
  • @akrun you found a job? Congrats man! – David Arenburg Jan 05 '16 at 13:49
  • @DavidArenburg Thanks, sort of. – akrun Jan 05 '16 at 13:50

0 Answers0