我有以下数据框
dd <- data.frame(b = c("High", "Medium", "Highest", "Low", "Not bad","Good", "V. Good"),
x = c("C3", "C1", "C4", "N2", "C2", "N1","N4"), x = c("5", "2", "3", "6", "7", "5","7") )因此,我希望使用变量X的手动顺序来转换数据帧。
例如:那是原版的
1 High C3 5
2 Medium C1 2
3 Highest C4 3
4 Low N2 6
5 Not bad C2 7
6 Good N1 5
7 V. Good N4 7但我想要的是一个新的数据帧,它基于X的值开始,但不是按字母顺序排列,而是按我选择的顺序随机排列,例如:
the first row has x=C1, the second have x=C2, the third have x=N4, ...etc如何做到这一点??
谢谢
发布于 2012-02-22 17:44:15
因为x列是一个因子,所以您可以简单地确保它的级别是您想要的顺序。
# New sorting order
desired_order <- sample(levels(dd$x))
# Re-order the levels
dd$x <- factor( as.character(dd$x), levels=desired_order )
# Re-order the data.frame
dd <- dd[order(dd$x),]发布于 2012-02-22 17:20:25
如果您的data.frame确实足够小,可以手动重新排序,那么只需创建一个数字向量1:7,按照行应该出现的方式进行排序。例如:
dd[c(2,5,7,1,4,3,6),]
b x x.1
2 Medium C1 2
5 Not bad C2 7
7 V. Good N4 7
1 High C3 5
4 Low N2 6
3 Highest C4 3
6 Good N1 5或者,如果你真的想使用字符向量,你也可以通过行名来引用,如下所示:
rownames(dd) <- as.character(dd$x)
dd[c("C1","C2","N4","C3","N2","C4","N1"),]
b x x.1
C1 Medium C1 2
C2 Not bad C2 7
N4 V. Good N4 7
C3 High C3 5
N2 Low N2 6
C4 Highest C4 3
N1 Good N1 5https://stackoverflow.com/questions/9391910
复制相似问题