Reputation: 11
I'm coding in R, and I want to replace all the values within a given vector which are over 0.5 with 1, and any value which is under 0.5 with -1. I know how to do this with two sequential calls to "replace" such as:
my_nums <- c(0.2,0.8,0.3,0.4)
my_nums_adj_temp <- replace(my_nums,my_nums>0.5,1)
my_nums_adj <- replace(my_nums_adj_temp,my_nums<0.5,-1)
And so "my_nums" goes from
> my_nums
[1] 0.2 0.8 0.3 0.4
to
> my_nums_adj
[1] -1 1 -1 -1
But is there a way to do this with just a single call to "replace"?
Upvotes: 1
Views: 70
Reputation: 269905
This returns the same value as the code in the question; however, if you really wanted to return 0 for an input component if that input is .5 (rather than returning .5 which is what the code in the question returns) then omit the second term or if you wanted to return some other value in that case replace the second .5 with that value.
sign(my_nums - .5) + .5 * (my_nums == .5)
## [1] -1 1 -1 -1
If you wanted to return 1 if the input is greater than or equal to .5 and -1 if it is less than we could use this. For each component of the input, only one of the two terms can be non-zero so the result will be 1 or -1 for each component.
(my_nums >= .5) - (my_nums < .5)
Upvotes: 1