I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.
E.g.:, I have this dataf
Another solution similar to @userR, but rather than creating each column individually, this creates a list of expressions that get evaluated all at once. It may still suffer the same "don't splice data frames into calls with !!!" fault that was mentioned in the comments since it uses select(.), but I thought I would post anyways.
library(rlang)
library(dplyr)
df <- data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA),
DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5),
DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA),
DV2_C=c(NA,NA,5), FACT = c("A","B","C"))
create_DV <- function(num) {
DV_name <- sym(paste0("DV_", num))
DV_char <- paste0("DV", num)
expr(!! DV_name := select(., contains(!! DV_char)) %>% rowSums(na.rm = TRUE))
}
DV_expr_list <- c(1,2) %>%
lapply(create_DV)
df %>%
mutate(
!!! DV_expr_list
)
#> ID DV1_A DV1_B DV1_C DV2_A DV2_B DV2_C FACT DV_1 DV_2
#> 1 1 1 NA NA 3 NA NA A 1 3
#> 2 2 NA 4 NA NA 3 NA B 4 3
#> 3 3 NA NA 5 NA NA 5 C 5 5