Reputation: 3021
I would like to take a vector, for example:
X <- c(1,2,3,-1,-2,-3)
and add 1 (or any other number fixed in advance) to the entries in which the values are negative, to produce
1,2,3,0,-1,-2
Is there a slick way to do this ?
Upvotes: 3
Views: 139
Reputation: 2203
One can use which command also :
X <- c(1,2,3,-1,-2,-3)
X[which(X < 0)] <- X[which(X < 0)] +1
Upvotes: 0
Reputation: 263362
Submitted in the R Golf competition for this problem:
X+(X<0)
Works because (X<0) will get coerced 1 for any desired case and 0 for others.
Upvotes: 8
Reputation: 174813
An alternative that is vectorised but slightly more verbose is:
> X <- c(1,2,3,-1,-2,-3)
> want <- X < 0
> X[want] <- X[want] + 1
> X
[1] 1 2 3 0 -1 -2
The key step is to generate indices where X is negative (want
). We then use this to index X
and add 1 to these only.
Whether the vectorisation outweighs the number of function calls involved above I leave to others to discuss (I doubt it make any difference for most problems).
Upvotes: 7
Reputation: 60868
Perhaps not the most readable solution, but I'll still post it for the fun of it:
> pmax(X, X+sign(X)*(-1))
[1] 1 2 3 0 -1 -2
Upvotes: 3