我有一个old_df看起来像
old_df <- data.frame(Name = c("A", "A","A","B", "B", "C", "D", "E", "E"),
Value = c(1, 1, 1, 2, 2, 3, 4, 5, 5))
我想通过将Name保留在新数据中来更新此old_df并使用新的更新值。
new <- data.frame(Name = c("A", "E",),
Value = c(100, 500))
新输出看起来像
A 100
A 100
A 100
B 2
B 2
C 3
D 4
E 500
E 500
答案 0 :(得分:2)
您可以使用match
并将来自不匹配值的NA
替换为旧值,即
old_df$new_val <- new$Value[match(old_df$Name, new$Name)]
old_df$new_val[is.na(old_df$new_val)] <- old_df$Value[is.na(old_df$new_val)]
或使用 dplyr ,
library(dplyr)
old_df %>%
left_join(new, by = 'Name') %>%
mutate(Value.y = replace(Value.y, is.na(Value.y), Value.x[is.na(Value.y)]))
两者都给予,
Name Value new_val 1 A 1 100 2 A 1 100 3 A 1 100 4 B 2 2 5 B 2 2 6 C 3 3 7 D 4 4 8 E 5 500 9 E 5 500
答案 1 :(得分:1)
另一种选择是使用data.table
library(data.table)
setDT(old_df)[new, Value := i.Value, on = .(Name)]
old_df
# Name Value
#1: A 100
#2: A 100
#3: A 100
#4: B 2
#5: B 2
#6: C 3
#7: D 4
#8: E 500
#9: E 500