简体   繁体   中英

Applying a function with two arguments using Lapply

I have created a test function, called testFunc which expects two arguments.

testFunc<-function(x,y){
  length(x)
  nrow(y)
}

Now I want to use lappy to apply this function to a list, keeping the y argument fixed.

Consider a test list, testList:

testList<-list(a=c(1,2,3,4,5,5,6),b=c(1,2,4,5,6,7,8))

Can we use lapply to run testFunc on testList$a and testList$b with same value of y?

I tried this call:

lapply(X = testList, FUN = testFunc, someDataFrame)

But I am always getting the length of someDataFrame as the output. Am I missing something obvious.

Change your function to

testFunc<-function(x,y){
  return(c(length(x), nrow(y)))
}

By default, a R function returns the last evaluated value

最简单的方法是使用命名变量:

lapply(X = testList, FUN=testFunc, y=someDataFrame)

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