gpt4 book ai didi

r - 如果满足条件,则向行添加特定值 - 在 R 中

转载 作者:行者123 更新时间:2023-12-02 00:57:35 24 4
gpt4 key购买 nike

我必须使用不同行数的数据框 df_a 和 df_b。这是我的数据结构的示例。

df_a

id   ident   var
1 Test1
2 Test1
3 Test2
4 Test1
5 Test3

df_b

id   ident   var
1 Test1 26
2 Test2 59

现在我想将 df_b$var 复制到 df_a$var,但前提是标识匹配。

结果需要如下所示:

df_a

id   ident   var
1 Test1 26
2 Test1 26
3 Test2 59
4 Test1 26
5 Test3 NA

我不太确定该怎么做 - 有人可以帮忙吗?

最佳答案

使用您的数据:

#I have removed the var column as, 1) it is blank in your case
#and 2) it will be filled in any way
df_a <- read.table(header=T, text='id ident
1 Test1
2 Test1
3 Test2
4 Test1
5 Test3')

df_b <- read.table(header=T, text='id ident var
1 Test1 26
2 Test2 59')

这是基于 R 的:

#df_a stays as it is since you need all the columns
#from df_b we just need indent for the link and var to be added
#the by argument indicates the "link" column
#all.x=TRUE states that all columns from df_a will be kept in the result
merge(df_a, df_b[c('ident','var')], by='ident', all.x=TRUE)

ident id var
1 Test1 1 26
2 Test1 2 26
3 Test1 4 26
4 Test2 3 59
5 Test3 5 NA

关于r - 如果满足条件,则向行添加特定值 - 在 R 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32845648/

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