[英]R - order a data.frame by column name AS CHARACTER
I understand that I can order a data.frame as such:我知道我可以这样订购 data.frame:
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?有没有办法将“B”转换为 B 以便识别列? 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)?
R(字符标识符与非字符标识符)中是否有一些术语来描述这个问题空间?
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):要订购多个列,您需要使用 do.call (帮助页面中的示例):
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") ] ), ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.