Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - order a data.frame by column name AS CHARACTER

Tags:

r

I understand that I can order a data.frame as such:

test = data.frame(A=c(4,2,4), B=c(8,3,2))
ordered = test[with( test, order(A,B)) , ]

But how do I accomplish the same thing when the columns are specified by column name as character variable? This doesn't seem to work:

test = data.frame(A=c(4,2,4), B=c(8,3,2))
cols = c( "A" , "B" )
ordered = test[ with( test, order(cols )) , ]

Is there a way to convert "B" to B so that the column is recognized? I seem to have this problem quite often with functions that take column name inputs. Is there some term to describe this problem-space in R (character identifier versus non-character identifier)?

like image 216
SFun28 Avatar asked Jul 01 '11 19:07

SFun28


1 Answers

Try instead:

ordered = test[ with( test, order(B)) , ]

Or:

 ordered2 = test[ order( test[["B"]] ) , ]

The second form would allow you to do something like:

colnm <- "B"
ordered2 = test[ order(test[[colnm]]) , ]

For more than one column to order you need to use do.call (example from the help page):

d4 <- data.frame(x = round(   rnorm(100)), y = round(10*runif(100)),
                  z = round( 8*rnorm(100)), u = round(50*runif(100)))
d4s <- d4[ do.call(order, d4[ , c("x", "y") ] ), ]
like image 133
IRTFM Avatar answered Oct 21 '22 01:10

IRTFM