【发布时间】:2018-05-22 00:25:39
【问题描述】:
我最近不得不编译一个学生分数的数据框(每个学生一行,id 列和几个整数值列,每个分数组件一个)。我必须将一个“主”数据帧和几个“校正”数据帧(主要包含 NA 和一些对主数据的更新)组合起来,以便结果包含来自主数据的最大值和所有更正。
我成功复制粘贴了一系列mutate() 调用,这很有效(参见下面的示例),但在我看来并不优雅。我想做的不是复制和粘贴,而是使用map2 和两个列列表来成对比较列。类似的东西(显然不能这样工作):
list_of_cols1 <- list(col1.x, col2.x, col3.x)
list_of_cols2 <- list(col1.y, col2.y, col3.y
map2(list_of_cols1, list_of_cols2, ~ column = pmax(.x, .y, na.rm=T))
我似乎无法想办法做到这一点。我的问题是:如何指定这样的列列表并在 dplyr 管道中的一个 map2() 调用中对它们进行变异,或者甚至有可能——我都弄错了吗?
最小工作示例
library(tidyverse)
master <- tibble(
id=c(1,2,3),
col1=c(1,1,1),
col2=c(2,2,2),
col3=c(3,3,3)
)
correction1 <- tibble(
id=seq(1,3),
col1=c(NA, NA, 2 ),
col2=c( 1, NA, 3 ),
col3=c(NA, NA, NA)
)
result <- reduce(
# Ultimately there would several correction data frames
list(master, correction1),
function(x,y) {
x <- x %>%
left_join(
y,
by = c("id")
) %>%
# Wish I knew how to do this mutate call with map2
mutate(
col1 = pmax(col1.x, col1.y, na.rm=T),
col2 = pmax(col2.x, col2.y, na.rm=T),
col3 = pmax(col3.x, col3.y, na.rm=T)
) %>%
select(id, col1:col3)
}
)
结果是
> result
# A tibble: 3 x 4
id col1 col2 col3
<int> <dbl> <dbl> <dbl>
1 1 1 2 3
2 2 1 2 3
3 3 2 3 3
【问题讨论】:
-
澄清一下,只有当值大于
master中的值时才应该进行更正? -
问得好,但不,我们的目标是在
master和correction1(以及correction2、correction3等)表中找到最大值。