0

I have two data frames like this:

df.1 <- data.frame(
     var.1 = sample(1:10),
     code = sample(c("A", "B", "C"), 10, replace = TRUE))

df.2 <- data.frame(
    var.2 = sample(1:3),
    row.names=c("A","B","C"))

What I need to do is to add a third column df.1$var.2 which, for each value in df.1$code take the value from df.2$var.2 accordingly to their row name.

I got to this point but with no success.. Suggestions?

for (i in 1:length(df.1$code)){
    if(df.1$code[i] == rownames(df.2))
    df.1$var.2[i] <- df.2$var.2
    }
demongolem
  • 9,474
  • 36
  • 90
  • 105
matteo
  • 645
  • 3
  • 10
  • 18

2 Answers2

2

You mean like this:

df.2$code <- rownames(df.2)
> merge(df.1,df.2,by = "code")
   code var.1 var.2
1     A     5     1
2     B     3     2
3     B     2     2
4     B     7     2
5     B    10     2
6     C     8     3
7     C     4     3
8     C     1     3
9     C     9     3
10    C     6     3
joran
  • 169,992
  • 32
  • 429
  • 468
0

Or, join() from the plyr package to preserve the order of df.1

df.2$code <- rownames(df.2)
library(plyr)
join(df.1, df.2, by = "code")

   var.1 code var.2
1      7    B     2
2      2    A     1
3      3    C     3
4      6    B     2
5     10    C     3
6      4    C     3
7      1    C     3
8      8    B     2
9      9    A     1
10     5    C     3
Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122