我有以下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
. . .
. . .
我希望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
. . .
. . .
可以通过对每个值使用以下内容来完成'mannualy':
df2[df2==1] <- 'this'
df2[df2==2] <- 'that'
.
.
等等,但有没有办法做到这一点而不是mannualy?
答案 0 :(得分: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"))
答案 1 :(得分:3)
你可以这样做:
library(qdapTools)
df2$VALUE <- lookup(terms = df2$VALUE, key.match = df1)
请注意,要使其生效,您需要df1
中的正确列顺序。来自?lookup
<强> key.match 强>
采取以下措施之一:(1)匹配键的两列data.frame 和重新分配列,(2)一个命名的向量列表(注意:如果 data.frame或命名列表不提供密钥重新分配)或(3)a 单矢量匹配键。
给出了:
# id VALUE
#1 1 theOther
#2 2 another
#3 3 that
#4 4 this
#5 5 another
#6 6 that
#7 7 theOther