Reputation: 33950
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
Upvotes: 2
Views: 82
Reputation: 21502
another approach:
bar <- function(x) {
as.vector(matrix(c(x,x+5),nrow=2,byrow=TRUE))
}
Upvotes: 2
Reputation: 1045
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)
Upvotes: 1