我有两个数据帧。数据框架A具有许多观察/行,每个观察值的ID和许多其他列。对于观测值x的子集,一组列的值丢失/Na。数据框架B包含X中的观测值子集(可以使用ID在数据框架上匹配的观测值(和具有与数据框架A中相同名称的变量,但包含值以替换具有缺失/缺失/的列中缺少值的值Na。
我的代码下面(使用联接操作(仅添加列而不是替换缺失值。对于B中的每个其他变量(让我们命名W(,结果表产生W.X和W.Y。
library(dplyr)
foo <- data.frame(id = seq(1:6), x = c(NA, NA, NA, 1, 3, 8), z = seq_along(10:15))
bar <- data.frame(id = seq(1:2), x = c(10, 9))
dplyr::left_join(x = foo, y = bar, by = "id")
我试图根据ID中的B中的值替换A中的丢失值,但是由于我有很多列和许多行,因此以有效的方式替换了B中的值。我的目标是:
id x z
1 1 10 1
2 2 9 2
3 3 NA 3
4 4 1 4
5 5 3 5
6 6 8 6
一个想法是加入后使用ifelse((,但是输入所有变量的Ifelse((函数是不可行的。是否有一种方法可以简单地执行此操作,而无需数据库加入,或者有没有办法在.x中以.x终止的所有列中应用一个函数,以替换.x中的值,如果丢失了.x的值,则在.y中替换值?
另一个尝试仅应为一个分配操作的尝试。再次使用 @alistaire的数据:
vars <- c("x","y")
foo[vars] <- Map(pmax, foo[vars], bar[match(foo$id, bar$id), vars], na.rm=TRUE)
foo
# id x y z
#1 1 10 1 1
#2 2 9 2 2
#3 3 NA 3 3
#4 4 1 4 4
#5 5 3 5 5
#6 6 8 6 6
edit
更新答案以@Alistaire的示例数据框架。
我们可以使用mapply
扩展下面给出的相同答案,以便它可以处理foo
和bar
的多个列。
在两个数据范围之间找到常见的列并对其进行排序,使其处于相同的顺序。
vars <- sort(intersect(names(foo), names(bar))[-1])
foo[vars] <- mapply(function(x, y) {
ind = is.na(x)
replace(x, ind, y[match(foo$id[ind], bar$id)])
}, foo[vars], bar[vars])
foo
# id x y z
#1 1 10 1 1
#2 2 9 2 2
#3 3 NA 3 3
#4 4 1 4 4
#5 5 3 5 5
#6 6 8 6 6
原始答案
我认为这可以做您想要的:
foo[-1] <- sapply(foo[-1], function(x) {
ind = is.na(x)
replace(x, ind, bar$x[match(foo$id[ind], bar$id)])
})
foo
# id x z
#1 1 10 1
#2 2 9 2
#3 3 NA 3
#4 4 1 4
#5 5 3 5
#6 6 8 6
对于每个列(id
除外(,我们在foo
中找到缺失值,并用bar
的相应值替换它。
如果您不介意冗长的基础方法,那么您可以使用merge()
轻松完成此操作,并仔细的数据框架子集。
df <- merge(foo, bar, by="id", all.x=TRUE)
names(df) <- c("id", "x", "z", "y")
df$x[is.na(df$x)] <- df$y[is.na(df$x)]
df <- df[c("id", "x", "z")]
> df
id x z
1 1 10 1
2 2 9 2
3 3 NA 3
4 4 1 4
5 5 3 5
6 6 8 6
您可以在非组列的相交上迭代dplyr::coalesce
。它不是优雅的,但应该很好地扩展:
library(tidyverse)
foo <- data.frame(id = seq(1:6),
x = c(NA, NA, NA, 1, 3, 8),
y = 1:6, # add extra shared variable
z = seq_along(10:15))
bar <- data.frame(id = seq(1:2),
y = c(1L, NA),
x = c(10, 9))
# names of non-grouping variables in both
vars <- intersect(names(foo), names(bar))[-1]
foobar <- left_join(foo, bar, by = 'id')
foobar <- vars %>%
map(paste0, c('.x', '.y')) %>% # make list of columns to coalesce
map(~foobar[.x]) %>% # for each set, subset foobar to a two-column data.frame
invoke_map(.f = coalesce) %>% # ...and coalesce it into a vector
set_names(vars) %>% # add names to list elements
bind_cols(foobar) %>% # bind into data.frame and cbind to foobar
select(union(names(foo), names(bar))) # drop duplicated columns
foobar
#> # A tibble: 6 x 4
#> id x y z
#> <int> <dbl> <int> <int>
#> 1 1 10 1 1
#> 2 2 9 2 2
#> 3 3 NA 3 3
#> 4 4 1 4 4
#> 5 5 3 5 5
#> 6 6 8 6 6