2
A B 
2 3
5 7
7 4
2 8

Is there any way to swap specific observations? I am trying to swap the observations in A that are > than the observations in the same row of B. In the data.frame above the observation in the third row of column A (7) is > the observation in the third row of column B (4) my goal is to swap the two.

Desired output

A B
2 3
5 7
4 7
2 8

I have tried using an &

df$A[df$A > df$B] <- df$B[df$A > df$B] & df$B[df$A >df$B] <- df$A[df$A >df$B]

I have also tried a nested ifelse

ifelse(df$A > df$B, df$A[df$A > df$B] <- df$B[df$A > df$B],
    ifelse(df$A > df$B, df$B[df$A >df$B] <- df$A[df$A >df$B], df$b))

Any help would be very much appreciated.

Dre

Dre
  • 713
  • 1
  • 8
  • 27

1 Answers1

4

We can either loop over the rows using apply with MARGIN=1 and sort

df1[] <- t(apply(df1, 1, sort))
df1
#  A B
#1 2 3
#2 5 7
#3 4 7
#4 2 8

Or rearrange the values in 'A' and 'B' using pmax/pmin

transform(df1, A=pmin(A,B), B= pmax(A,B))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • The transform using `pmax/pmin` almost worked. When I used it a data.frame with my desired out appeared in my console but when I `view(df)` the data.frame was unchanged. I am not sure why that happened. – Dre Dec 07 '15 at 20:08
  • I am working with more than two columns so I didn't want to use the loop suggestion. Is there a way I could do the loop specifically on columns `A` and `B`? – Dre Dec 07 '15 at 20:12
  • for the first comment, `df1 <- transform(df1, ..)` and for second `df1[c('A','B')] <- ...` use the same subset on rhs – akrun Dec 07 '15 at 20:16