Reputation: 157
Say I have multiple if conditions, under which different values are assigned to a variable. For instance:
x <- rep(c(1, 2, 3, 4, 5, 6, 7, 8), 4)
for(i in length(x)) {
if(x[i] == 2) {
x[i] <- 10
}
if(x[i] == 4) {
x[i] <- 12
}
## and there are more similar if conditions
## ......
}
In general, I'd like to replace the numbers in this vector with other numbers according to specific conditions. Is there a simpler way to do this without writing such a long loop?
Upvotes: 2
Views: 364
Reputation: 99331
You don't necessarily need any if
statements. You could create a vector of values you want to change x
to, then change them all directly with replace
> x <- rep(c(1, 2, 3, 4, 5, 6, 7, 8), 4)
> inds <- sapply(c(2, 4), function(z) which(x == z))
> vals <- c(rep(10, nrow(inds)), rep(12, nrow(inds)))
> replace(x, inds, vals)
## [1] 1 10 3 12 5 6 7 8 1 10 3 12 5 6 7 8 1 10 3 12 5 6
## [23] 7 8 1 10 3 12 5 6 7 8
Upvotes: 3
Reputation: 94182
If your x
is small non-zero integers, make a lookup table as a simple vector:
lut=c(10,12,13,55,99,12,12,12,99,1010)
lut[x]
[1] 10 12 13 55 99 12 12 12 10 12 13 55 99 12 12 12 10 12 13 55 99 12 12 12 10
[26] 12 13 55 99 12 12 12
For other keys, use a list and characterify all the things:
> lut = list("999"=1, "8"=2, "foo"=223)
> unlist(lut[c("999","999","8","8","8","foo")])
999 999 8 8 8 foo
1 1 2 2 2 223
Upvotes: 4