Richard Telford
Richard Telford

Reputation: 9923

Unexpected result from plyr::aaply

I am trying to sort data.frame test so that each row is alphabetically arranged.

> test
        old     new
32  Aju.dec Cli.pol
151 Kob.pyg Fes.spp
57  Aju.dec Cli.pol
170 Kob.pyg Kob.cer

This can, of course, be done several ways.

I get the expected result by transposing the results of apply

t(apply(test, 1, sort))
    [,1]      [,2]     
32  "Aju.dec" "Cli.pol"
151 "Fes.spp" "Kob.pyg"
57  "Aju.dec" "Cli.pol"
170 "Kob.cer" "Kob.pyg"

But with plyr::aaply I get an array

> plyr::aaply(test, 1, sort)
, ,  = old

         new
old       Cli.pol   Fes.spp   Kob.cer  
  Aju.dec "Aju.dec" NULL      NULL     
  Kob.pyg NULL      "Fes.spp" "Kob.cer"

, ,  = new

         new
old       Cli.pol   Fes.spp   Kob.cer  
  Aju.dec "Cli.pol" NULL      NULL     
  Kob.pyg NULL      "Kob.pyg" "Kob.pyg"

And with plyr::adply I get the unsorted data.frame returned

plyr::adply(test, 1, sort)
      old     new
1 Aju.dec Cli.pol
2 Kob.pyg Fes.spp
3 Aju.dec Cli.pol
4 Kob.pyg Kob.cer

I can use the apply, but would be grateful if anyone could explain what I have misunderstood about plyr::aaply and plyr::adply. If there is a dplyr solution, I would be even happier.

data

test <- structure(list(old = c("Aju.dec", "Kob.pyg", "Aju.dec", "Kob.pyg"
  ), new = c("Cli.pol", "Fes.spp", "Cli.pol", "Kob.cer")), .Names = c("old", 
  "new"), row.names = c(32L, 151L, 57L, 170L), class = "data.frame")

Upvotes: 0

Views: 49

Answers (1)

ira
ira

Reputation: 2644

I have the feeling that adply is not capable to "break down" the structure of the dataframe - i.e. it performs the function as expected, but it can't move observations between the two columns. You can convert the data.frame to matrix and then it will work.

That your syntax is otherwise correct can be seen by e.g. applying order or rank function to the data.frame.

adply(as.matrix(test), 1, sort)

Upvotes: 1

Related Questions