Changing values ​​between two data frames in R

I have the following data.frames (sample):

>df1
  number             ACTION
1      1               this
2      2               that
3      3           theOther
4      4            another

>df2
      id            VALUE
1      1                3
2      2                4
3      3                2
4      4                1
4      5                4
4      6                2
4      7                3
.      .                .
.      .                .

      

I would like df2 to become the following:

>df2
      id            VALUE
1      1         theOther
2      2          another
3      3             that
4      4             this
4      5          another
4      6             that
4      7         theOther
.      .                .
.      .                .

      

This can be done "mannualy" using the following for each value:

df2[df2==1] <- 'this'
df2[df2==2] <- 'that'
       .
       .

      

and so on, but is there a non-mannualy way to do this?

+3


source to share


2 answers


Try

df2$VALUE <- setNames(df1$ACTION, df1$number)[as.character(df2$VALUE)]
df2
#   id    VALUE
#1  1 theOther
#2  2  another
#3  3     that
#4  4     this
#5  5  another
#6  6     that
#7  7 theOther

      

Or use match



df2$VALUE <- df1$ACTION[match(df2$VALUE, df1$number)]

      

data

df1 <- structure(list(number = 1:4, ACTION = c("this", "that", 
"theOther", 
"another")), .Names = c("number", "ACTION"), class = "data.frame", 
row.names = c("1", "2", "3", "4"))

df2 <- structure(list(id = 1:7, VALUE = c(3L, 4L, 2L, 1L, 4L, 2L, 3L
 )), .Names = c("id", "VALUE"), class = "data.frame", row.names = c("1", 
 "2", "3", "4", "5", "6", "7"))

      

+3


source


You can do:

library(qdapTools)
df2$VALUE <- lookup(terms = df2$VALUE, key.match = df1)

      

Note that you need the correct column order in the df1

. Of?lookup



key.match

Accepts one of the following values: (1) a two-channel data.frame of a match key and a reassignment column, (2) a named list of vectors (Note: if data.frame or a named list that does not require a reassignment key), or (3) a key of a single vector match.

What gives:

#  id    VALUE
#1  1 theOther
#2  2  another
#3  3     that
#4  4     this
#5  5  another
#6  6     that
#7  7 theOther

      

+3


source







All Articles