我在order
周圍寫了這個小小的包裝,但我擔心我的實現是跛腳。我蜷縮在角落裏,等待着R的神命令或算法的效率要刺我的人體工程學鍵盤:-(有沒有更簡單的方法來重新排列數據的列值?
set.seed(1001)
height <- rnorm(6, mean = 1, sd = 0.2)
weight <- rnorm(6, mean = 100, sd = 15)
id <- 1:6
dd <- data.frame(id, height, weight)
# Here's the function I came up with
ReorderDataByColumn <- function(x, column) {
ordered.indices <- order(x[ ,paste(column)])
return(x[ordered.indices, ])
}
#And here are its results
> ReorderDataByColumn(dd, column = "height")
id height weight
4 4 0.4986928 76.09430
5 5 0.8885377 104.53967
3 3 0.9629449 86.38809
2 2 0.9644905 90.65584
6 6 0.9712881 124.51589
1 1 1.4377296 116.37253
> ReorderDataByColumn(dd, column = "weight")
id height weight
4 4 0.4986928 76.09430
3 3 0.9629449 86.38809
2 2 0.9644905 90.65584
5 5 0.8885377 104.53967
1 1 1.4377296 116.37253
6 6 0.9712881 124.51589
我現在很困惑。在這種情況下'paste()'實際上做了什麼? –
+1對於問我想知道我自己的東西... – joran
請參閱這裏的答案几個更好的選擇:http://stackoverflow.com/q/1296646/210673 – Aaron