R functional comparison of two columns

83 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

You can use logical subsetting like so:

set.seed(123)
x <- sample(1:100, 25)
y <- sample(1:100, 25)


x[3] <- 10
y[3] <- 10

x.orig <- x
x[x != y] <- x[x != y] +1

cbind(y, x.orig, x)

#      y x.orig  x
# [1,] 71     29 30
# [2,] 54     79 80
# [3,] 10     10 10
# [4,] 29     86 87
# [5,] 15     91 92
# [6,] 92      5  6
# [7,] 85     50 51
# [8,] 65     83 84
# [9,] 74     51 52
# [10,]  3     42 43
# [11,] 44     87 88
# [12,] 68     98 99
# [13,] 20     60 61
# [14,] 28     94 95
# [15,] 88      9 10
# [16,] 13     77 78
# [17,] 35     21 22
# [18,] 84      4  5
# [19,] 31     27 28
# [20,] 94     78 79
# [21,] 12     72 73
# [22,] 19     55 56
# [23,] 37     90 91
# [24,] 21     85 86
# [25,] 66     81 82