Hello.
I've recently come across an interesting problem, where I had to do the following>
Suppose we have two integer valued columns. For each value in the first, I have to check, whether that value is not the same as the value at the same index in the second column, and if so, add 1 to the value in the first column.
I solved this with a for loop, where I iterated through indices and added values correspondingly, but as this is R, I hope there is some more R-ish way to solve this. I was thinking in the lines of>
sapply(column1, function(x) ifelse(x != column2, x+1, x))
but of course, this does not yet work. Can this be done in such a manner?
This seems to work:
df <- data.frame(a = c(1,2,3,4,5), b = c(1,3,3,4,4)) df$a <- ifelse(df$a != df$b, df$a+1, df$a)
sample data looks as this in a table:
a b 1 1 1 2 2 3 3 3 3 4 4 4 5 5 4
after running the above code it looks like this:
a b 1 1 1 2 3 3 3 3 3 4 4 4 5 6 4