gpt4 book ai didi

r - 在 R 中的两个数据帧之间更改值

转载 作者:行者123 更新时间:2023-12-01 10:40:09 24 4
gpt4 key购买 nike

我有以下 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
. . .
. . .

可以通过对每个值使用以下内容来“手动”完成:

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

等等,但有没有办法不用手动操作呢?

最佳答案

尝试

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

关于r - 在 R 中的两个数据帧之间更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30832023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com