1

I have two data frames with matching cells.

    v <- data.frame(c1=c(30,15,3), c2=c(10,25,2), c3=c(20,35,4))
    w <- data.frame(c1=c("thirty","fifteen","three"), c2=c("ten","twenty-five","two"), c3=c("twenty","thirty-five","four"))

I need to sort each row of both without resorting to (slow) loops. To sort v (which will determine the order of the other data frame too) I use the method recommended here:

    v.sorted <- t(apply(v, 1, sort))

How can I manipulate data frame w so that it matches the sorted version of v?

Thanks in advance!

Community
  • 1
  • 1
emagar
  • 985
  • 2
  • 14
  • 28

1 Answers1

1

We can use lapply with order

do.call(rbind, lapply(seq_len(nrow(v)), function(i) 
     as.character(unlist(w[i,])[order(unlist(v[i,]))])))
#     [,1]      [,2]          [,3]         
#[1,] "ten"     "twenty"      "thirty"     
#[2,] "fifteen" "twenty-five" "thirty-five"
#[3,] "two"     "three"       "four"       
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks @akrun! Your solution works for row 1, but not the rest. Actually, the list that `lapply(seq_len(nrow(v)), function(i) w[i,][order(v[i,])])` makes is correct. Is `rbind` missing something? – emagar Mar 03 '16 at 18:42
  • 1
    @emagar Sorry, forgot about the `unlist` part. It should work now. – akrun Mar 03 '16 at 18:46