Unwanted sorted behavior on result of vector-concatenation function

妖精的绣舞 提交于 2019-12-11 02:15:32

问题


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)))


来源:https://stackoverflow.com/questions/22558395/unwanted-sorted-behavior-on-result-of-vector-concatenation-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!