Adding 1 to some elements in a vector

71 Views Asked by At

Say for instance I have a vector of

x <- c(10,1,1) 

and I want to add 1 only to an element which has the value 1 while the 10 remains as it is. How do I go about that?

The answer must be in the form of a vector.

# This is what I tried but it added 1 to every element
x <- c(10,1, 1)

for (j in 1:length (x))
 x[j] = x[j] + 1
}
print (x)
[1] 11 2 2
4

There are 4 best solutions below

0
benson23 On

You can take advantage of logical comparison, where TRUE is coerced into 1 and FALSE is coerced into 0 upon arithmetic operation.

x + (x != 10)
[1] 10  2  2
0
MetehanGungor On

If the focused value is 1, this code may work.

for (j in 1:length(x)) {
  if(x[j] == 1) {
    x[j] <- x[j] + 1 }
}

x
0
IRTFM On

Vectorized solutions are likely to perform better than loop methods. Assignment can be on the basis of logical vector:

x[x == 1] <- x[x == 1]+1
0
Miff On

Just to add another option which may be clearer using the ifelse function:

x <- x + ifelse(x==1, 1, 0)
x
#[1] 10  2  2