Reputation: 634
I have a list of dataframes and I want to apply a custom function to it using lapply
Here is my function:
rename_cols_pattern <- function (df, pattern, replacement = "") {
names(df) <- gsub(names(df), pattern = pattern, replacement = replacement)
}
How do I use this function with lapply? This does not work because the df variable is missing. How do I pass in the df variable which would be the dataframes in the di_data list
di_data <- lapply(di_data, rename_cols_pattern(pattern = "X"))
I can get this to work like so:
di_data <- lapply(di_data, function(x) {
names(x) <- gsub(names(x), pattern = "X", replacement = "")
x
})
However I want the function to be separate and want to understand how to achieve this
Upvotes: 1
Views: 158
Reputation: 4151
rename_with was created to solve these kind of problems
library(tidyverse)
mtcars %>%
rename_with(.fn = ~ str_remove_all(.x,"X"))
Upvotes: 0
Reputation: 72623
You probably missed the return
statement of your function.
rename_cols_pattern <- function(df, pattern, replacement="") {
names(df) <- gsub(names(df), pattern=pattern, replacement=replacement)
return(df)
}
Normal usage:
rename_cols_pattern(dat, pattern="X", replacement="COL")
# COL1 COL2 COL3 COL4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
Using lapply
:
lapply(list(dat, dat), rename_cols_pattern, pattern="X", replacement="COL")
# [[1]]
# COL1 COL2 COL3 COL4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
#
# [[2]]
# COL1 COL2 COL3 COL4
# 1 1 4 7 10
# 2 2 5 8 11
# 3 3 6 9 12
Data:
dat <- structure(list(X1 = 1:3, X2 = 4:6, X3 = 7:9, X4 = 10:12), class = "data.frame", row.names = c(NA,
-3L))
Upvotes: 2