Question

I apply a simple anonymous function to return c(x,x+5) on the sequence 1:5

I expect to see c(1,6,2,7,3,8,4,9,5,10) (the concatenation of the subresults) but instead the result vector is unwantedly sorted. What is doing that and how do I prevent it?

> (function(x) c(x,x+5)) (1:5)
 [1]  1  2  3  4  5  6  7  8  9 10

However applying the function on each individual argument is right:

> (function(x) c(x,x+5)) (1)
[1] 1 6
> (function(x) c(x,x+5)) (2)
[1] 2 7
...
> (function(x) c(x,x+5)) (5)
[1]  5 10
Was it helpful?

Solution 3

You could try this to spoof the order of operations:

foo<-function(x) {   
      bar<-cbind(x,x+5)  
      as.vector(t(bar))

}
foo(1:5)

Or in one line form:

(function(x) as.vector(t(cbind(x,x+5)))) (1:5)

OTHER TIPS

another approach:

bar <- function(x) {
    as.vector(matrix(c(x,x+5),nrow=2,byrow=TRUE))
}

In this way it works:

   unlist(lapply(1:5, function(x) c(x, x+5)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top