简体   繁体   中英

How to pass argument into user defined function when using lapply

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

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))

rename_with was created to solve these kind of problems

library(tidyverse)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM