在R中的两个data.frames之间更改值
我有以下数据。帧(示例): 我希望df2变得如下所示:在R中的两个data.frames之间更改值,r,dataframe,R,Dataframe,我有以下数据。帧(示例): 我希望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
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'
.
.
df2[df2==1]试试看
数据
df1您可以:
library(qdapTools)
df2$VALUE <- lookup(terms = df2$VALUE, key.match = df1)
谢谢我更喜欢匹配
答案,因为它更具可读性:D
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
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"))
library(qdapTools)
df2$VALUE <- lookup(terms = df2$VALUE, key.match = df1)
# id VALUE
#1 1 theOther
#2 2 another
#3 3 that
#4 4 this
#5 5 another
#6 6 that
#7 7 theOther