简体   繁体   English

更改R中两个data.frame之间的值

[英]Changing values between two data.frames in R

I have the following data.frames(sample): 我有以下data.frames(示例):

>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 like the following: 我想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
.      .                .
.      .                .

It can be done 'mannualy' by using the following for each value: 可以通过对每个值使用以下内容来“mannualy”:

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

and so on, but is there a way to do it not mannualy? 等等,但有没有办法做到这一点而不是mannualy?

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 或者使用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"))

You could do: 你可以这样做:

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

Note that for this to work, you will need the proper columns order in df1 . 请注意,要使其正常工作,您需要在df1使用正确的列顺序。 From ?lookup ?lookup

key.match key.match

Takes one of the following: (1) a two column data.frame of a match key and reassignment column, (2) a named list of vectors (Note: if data.frame or named list supplied no key reassign needed) or (3) a single vector match key. 采用以下方法之一:(1)匹配键和重新分配列的两列data.frame,(2)一个命名的向量列表(注意:如果data.frame或命名列表未提供密钥重新分配)或(3) )单个矢量匹配键。

Which gives: 这使:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM