1

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.

5
  • Why don't you set your y to be fixed within the function and use only x as argument? i.e. testfunc <- function(x, y=...) {...} ? Commented May 12, 2016 at 12:06
  • @Sotos : The code as it is posted already does the job. But, I think Tushar wants to return length(x) and nrow(y) both Commented May 12, 2016 at 12:17
  • Yeah, I thought it didn't make much sense... Commented May 12, 2016 at 12:19
  • @vasanthcullen I am expecting it to print the values 7, nrow(someDataFrame) two times, since testList has two vectors. All it gives me is 7 and nrow(someDataFrame) once. Commented May 12, 2016 at 13:08
  • @vasanthcullen Yeah, got it. I should have used print, to print the number of rows. I think the point you made regarding R printing the last evaluated value was the reason. Thanks. Commented May 12, 2016 at 13:16

2 Answers 2

1

Change your function to

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

By default, a R function returns the last evaluated value

Sign up to request clarification or add additional context in comments.

Comments

1

Simplest way, use a named variable:

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

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.