1

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

1
  • does it need to be lapply? map has very good anonymous function support Commented Jun 18, 2020 at 9:45

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

Comments

0

rename_with was created to solve these kind of problems

library(tidyverse)

mtcars %>% 
  rename_with(.fn = ~ str_remove_all(.x,"X"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.