2

I'm trying to lapply a function over a list. Because my function intends to output 2 objects, I'm running into a problem. For each item in the list, running the function only outputs results from the second object.

Here is a vastly simplified example.

test<-function(x){
  a<-x+4
  b<-x/34
}
list<-c(3,4,5,6,6)
lapply(list,test)

# Outputs b:
[[1]]
[1] 0.08823529

[[2]]
[1] 0.1176471

[[3]]
[1] 0.1470588

[[4]]
[1] 0.1764706

[[5]]
[1] 0.1764706

How to I get the function to output both a and b?

3
  • In your test function, add a third line: return(a = a, b = b) Commented Jan 27, 2016 at 16:44
  • @Benjamin - You mean return(c(a = a, b = b)) (or list depending on preference). But return() is a bit pointless on the last line, just c(a = a, b = b) would be fine. Commented Jan 27, 2016 at 16:53
  • oops. I meant to put that in list, actually. as in return(list(a=a, b=b)) Commented Jan 27, 2016 at 16:54

1 Answer 1

3

The function is returning just the last line as it should. Try:

test<-function(x){
a<-x+4
b<-x/34
return(c(a,b))
}
list<-c(3,4,5,6,6)
lapply(list,test)
Sign up to request clarification or add additional context in comments.

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.