我有一种方法可以通过匹配 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_df
和 delta_test
并使用 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))
关于通过索引值将数据框中的值替换为另一个数据框中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63876960/