我有以下数据框
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
如何做到这一点??
谢谢
答案 0 :(得分:10)
由于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),]
答案 1 :(得分:0)
如果您的data.frame
确实足够小,可以手动重新排序,那么只需创建数字1:7
的向量,按照行显示的方式排序。 e.g:
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 5