在R中更改两个数据框之间的值

3

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
.      .                .
.      .                .

我希望df2变成如下所示:
>df2
      id            VALUE
1      1         theOther
2      2          another
3      3             that
4      4             this
4      5          another
4      6             that
4      7         theOther
.      .                .
.      .                .

可以通过手动使用以下内容为每个值执行:

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

等等,有没有一种不需要手动操作的方法来完成这个任务?

2个回答

3

尝试

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

或者使用match

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

数据

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"))

2
谢谢。我更喜欢match的答案,因为它更易读 :D - Mpizos Dimitris

3
你可以这样做:
library(qdapTools)
df2$VALUE <- lookup(terms = df2$VALUE, key.match = df1)

请注意,为了使此功能正常工作,您需要在df1中拥有正确的列顺序。请参考?lookup

key.match

接受以下之一:(1) 匹配键和重新分配列的两列数据框,(2) 命名向量列表(注意:如果提供数据框或命名列表,则不需要重新分配键),或者 (3) 单个向量匹配键。

它会给出:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接