0

consider 2 dataframes: p1 <- data.frame(x1 = c(5,8), y1=c(3,8)); p2 <- data.frame(x1 = c(2,10), y1=c(5,3))

I want to compare each value of p1 respectively to the value of p2 (same position), I tried:
ifelse( p1 < p2, p2 - p1, ifelse(p1 > p2, p1 + p2, 1))

I want have result: data.frame(x1 = c(7,2), y1=c(2,11))

but it seems ifelse work only on vectors and it returns a list.

do you have an idea?

DD chen
  • 169
  • 11

3 Answers3

3

If you convert p1 and p2 to matrices, your original ifelse() works:

p1 <- as.matrix(p1)
p2 <- as.matrix(p2)
p3 <- as.data.frame(ifelse( p1 < p2, p2 - p1, ifelse(p1 > p2, p1 + p2, 1)))
p3
  x1 y1
1  7  2
2  2 11
Ben Norris
  • 5,639
  • 2
  • 6
  • 15
1

You can try the code below

(p2-p1)*(p1<p2)+(p2+p1)*(p1>p2) + 1*(p1==p2)

or

p2 + p1*((p1>p2)-(p1<p2)) + 1*(p1==p2)

both of which will give

  x1 y1
1  7  2
2  2 11
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

Your attempt does not work because you are using ifelse on dataframe. You can convert your dataframe to matrix and it would work.

p1 <- as.matrix(p1)
p2 <- as.matrix(p2)
ifelse(p1 < p2, p2 - p1, ifelse(p1 > p2, p1 + p2, 1))

#     x1 y1
#[1,]  7  2
#[2,]  2 11

You can convert the above result to dataframe if needed.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213