简体   繁体   中英

Passing column name and data frame to custom function in R

I am trying to write a function in R that:

1) Receives a data frame and column name as parameters. 2) Performs an operation on the column in the data frame.

func <- function(col, df)
{
  col = deparse(substitute(col))
  print(paste("Levels: ", levels(df[[col]])))
}


func(Col1, DF)

func(Col2, DF)

mapply(func, colnames(DF)[1:2], DF)

Output

> func(Col1, DF)
[1] "Levels:  GREEN"  "Levels:  YELLOW"

> func(Col2, DF)
[1] "Levels:  0.1" "Levels:  1"  

> mapply(func, colnames(DF)[1:2], DF)
 Error in `[[.default`(df, col) : subscript out of bounds 

Two things :

  • in your function func , you apply deparse(substitute(col)) to an object col you expected is not a string. So it works with func(Col1, DF) . But in your mapply() call, your argument colnames(...) is a string, so it create an error. Same error obtained with func('Col1', DF) .

  • in a mapply() call, all arguments need to be a vector or a list. So you need to use list(df, df) , or if you don't want to replicate, remove the argument df of your function func .

This is one alternative that should work:

func <- function(col, df)
{
  print(paste("Levels: ", levels(df[,col])))
}

mapply(FUN = func, colnames(DF)[1:2], list(DF, DF))

Please have a look at the last comment of @demarsylvain - maybe a copy-paste error on your side, you should have done:

func <- function(col,df) {
  print(paste("Levels: ", levels(df[,col])))
}

mapply(FUN = func, c('Species', 'Species'), list(iris, iris))

you did:

func <- function(col) {
  print(paste("Levels: ", levels(df[,col])))
}

mapply(FUN = func, c('Species', 'Species'), list(iris, iris))

Please upvote and accept the solution of @demarsylvain, it works

EDIT to adress your comment:

To have a generic version for an arbitrary list of column names you can use this code, sorry for the loop :)

func <- function(col,df) {
  print(paste("Levels: ", levels(df[,col])))
}

cnames = colnames(iris)


i <- 1
l = list()
while(i <= length(cnames)) {
  l[[i]] <- iris
  i <- i + 1
}

mapply(FUN = func, cnames, l)

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