Reputation: 21
I need to change certain values in one vector depending on what the values are in the same places on in another vector. Below are my vectors:
r <- (1:20)
a <- c(54,54,54,54,55,55,50,0,0,0,0,0,0,1,1,1,1,1,56,57)
Basically if any of the values in 'a' are greater than or equal to and less than 20 (so any value in a that is 0-20) I want to change that value in 'r' to be itself -1. If the value in 'a' is greater than 20 or less than 0, then I want its value in 'r' to remain the same. So for the 8th spot in 'a' the value is 0 which is greater than/equal to 0 and less than 20 so I want the 8th spot in 'r' (has a value of 8) subtract by 1 (so now its value will be 7). But for the first spot in 'a', the value is 54 which is greater than 20 so the 1st value in r will remain the same. I assumed I needed to write a for loop for this and I started to but it's not doing what I need it to do. This is what I have so far.
for(i in a){
if (i >= 0 && i < 20){
r[i] = r[i]-1
} else {
r[i] = r[i]
}
}
When I run this code it returns r as
[1] -4 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 NA NA NA NA NA NA NA NA NA NA NA
[32] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
How can I get it to return the correct result which should look like this:
[1] 1 2 3 4 5 6 7 7 8 9 10 11 12 13 14 15 16 17 19 20
Thank you!
Upvotes: 1
Views: 1103
Reputation: 34441
You can do:
r - (a >= 0 & a < 20)
[1] 1 2 3 4 5 6 7 7 8 9 10 11 12 13 14 15 16 17 19 20
Upvotes: 1
Reputation: 101403
I guess a compact base R solution is to use ifelse
ifelse(a>=0 & a< 20,r-1,r)
which gives
> ifelse(a>=0 & a< 20,r-1,r)
[1] 1 2 3 4 5 6 7 7 8 9 10 11 12 13 14 15 16 17 19 20
Upvotes: 0
Reputation: 118
Maybe this would help,
r <- (1:20)
a <- c(54,54,54,54,55,55,50,0,0,0,0,0,0,1,1,1,1,1,56,57)
r[a >= 0 & a < 20] <- r[a >= 0 & a < 20] - 1
# [1] 1 2 3 4 5 6 7 7 8 9 10 11 12 13 14 15 16 17 19 20
You don't need a loop here the above answer is the most efficient.
Upvotes: 3
Reputation: 887148
We can loop through the sequence
for(i in seq_along(a)) if(a[i] >=0 && a[i] < 20) r[i] <- r[i] -1
r
#[1] 1 2 3 4 5 6 7 7 8 9 10 11 12 13 14 15 16 17 19 20
instead of the values of 'a' because r[54]
doesn't exist and assigning on that element results in NA
Upvotes: 1