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
You can take advantage of logical comparison, where
TRUEis coerced into 1 andFALSEis coerced into 0 upon arithmetic operation.