簡體   English   中英

R - 按列名作為字符訂購 data.frame

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

我知道我可以這樣訂購 data.frame:

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

但是,當列由列名指定為字符變量時,我該如何完成同樣的事情呢? 這似乎不起作用:

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

有沒有辦法將“B”轉換為 B 以便識別列? 對於采用列名輸入的函數,我似乎經常遇到這個問題。 R(字符標識符與非字符標識符)中是否有一些術語來描述這個問題空間?

改為嘗試:

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

或者:

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

第二種形式將允許您執行以下操作:

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

要訂購多個列,您需要使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM