繁体   English   中英

通过索引值用来自另一个数据帧的值替换数据帧中的值

[英]Replacing values in a dataframe with values from another dataframe by index values

我有一种通过匹配 id 值来替换数据帧中的值的方法。 这适用于小型数据集,但不适用于大型数据集。 有没有人对我如何使这个过程在计算上更有效有建议?

下面是我的 R 代码示例。 我正在使用 tidyverse 包。

# Delta Array small test
test_df <- data.frame(ID = c(1,2,3,4,5,6,7,8,8,9),
                  val = c(1,NA,3,4,5,6,7,8,NA,9))

delta_test <- data.frame(ID = c(2,8,9),
                     val = c(2,100,50))

test_df$val <- ifelse(is.na(delta_test$val[match(test_df$ID, delta_test$ID)]),
                  test_df$val,
                  delta_test$val[match(test_df$ID, delta_test$ID)])

test_df

您可以尝试将test_dfdelta_test连接test_df ,并使用coalesce选择第一个非 NA 值。

library(dplyr)

test_df <- test_df %>%
             left_join(delta_test, by = 'ID') %>%
             mutate(val = coalesce(val.y, val.x)) %>%
             select(ID, val)
test_df
#  ID val
#1   1   1
#2   2   2
#3   3   3
#4   4   4
#5   5   5
#6   6   6
#7   7   7
#8   8 100
#9   8 100
#10  9  50

在基础 R 中,这可以实现为:

test_df <- transform(merge(test_df, delta_test, by = 'ID', all.x = TRUE),
                     val = ifelse(is.na(val.y), val.x, val.y))

暂无
暂无

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

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