I have a simple function that works just fine on one data frame but doesn’t do anything when I use it in lapply
.
For example:
df1 <- data.frame(x = c(1:5), y = c(11:14, NA))
df2 <- data.frame(x = c(1:3, NA, 4), y = c(11:15))
mylist <- list(df1 = df1, df2 = df2)
ref <- data.frame(table = c("df1", "df2"), column = c("y", "x"))
updateCols <- function(table) {
tableName = deparse(substitute(table))
table %>%
mutate(across(all_of(filter(
ref, table == tableName) %>% pull(column)),
~ as.character(.) %>%
replace_na("\N")))
}
My updateCols() function applies a mutate on any columns in the reference list ref
, converting NA values to N
.
When I apply the function one data frame at a time, it works great.
df3 <- updateCols(df1)
df4 <- updateCols(df2)
newlist <- list(df3 = df3, df4 = df4)
print(newlist)
$df3
x y
1 1 11
2 2 12
3 3 13
4 4 14
5 5 \N
$df4
x y
1 1 11
2 2 12
3 3 13
4 \N 14
5 4 15
However, if I use lapply
with it, I don’t get any errors but the function doesn’t do anything.
newlist <- lapply(mylist, updateCols)
print(newlist)
$df1
x y
1 1 11
2 2 12
3 3 13
4 4 14
5 5 NA
$df2
x y
1 1 11
2 2 12
3 3 13
4 NA 14
5 4 15
Is this a problem with the filtering? Something off with mutate
? I’m at a loss.