I have a list of dataframes that contain a subset of columns. Excluding the identifier columns (id and n), all possible column names are included in a character vector called colors. I want to make so that if a dataframe, in this list of dataframes, is missing a column from colors, I want to put those missing columns into that dataframe and make those originally-missing columns NA.
This SO post demonstrates how to do this one column at a time, but considering the size of my real dataframe, I ideally would like to do it for all columns at once. I have included a reprex below with a working function that only does one color at a time and a non-working function that contains a loop.
set.seed(123)
library(tidyverse)
n <- c(1:10)
red <- sample(1:10, 10, replace = TRUE)
blue <- sample(1:10, 10, replace = TRUE)
yellow <- sample(1:10, 10, replace = TRUE)
green <- sample(1:10, 10, replace = TRUE)
pink <- sample(1:10, 10, replace = TRUE)
df1 <- data.frame(id = "1", n, red, blue, green)
df2 <- data.frame(id = "2", n, red, blue, green, pink)
df3 <- data.frame(id = "3", n, blue, yellow, green, pink)
df4 <- data.frame(id = "4", n, blue, yellow, pink)
df5 <- data.frame(id = "5", n, green)
lst <- list(df1, df2, df3, df4, df5)
# this works but only does red
red_func <- function(x) {
if (!'red' %in% names(x)) x <- x %>% add_column(red = NA)
else x
}
# failed attempted at loop
color_func <- function(z) {
colors <- c("red", "blue", "yellow", "green", "pink")
for (x in colors) {
if (!x %in% names(z)) z <- z %>% add_column(x = NA)
else z
}
}
test <- lapply(lst, color_func)
print(test[[1]])
#> NULL