我最近需要编译一个学生成绩数据框(每个学生一行,包含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
和correction1
(以及correction2
,correction3
等)表中找到最大值。 - user1642246