Unwanted sorted behavior on result of vector-conca

2019-07-18 15:46发布

问题:

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

回答1:

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)


回答2:

another approach:

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


回答3:

In this way it works:

   unlist(lapply(1:5, function(x) c(x, x+5)))