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)?
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") ] ), ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With