我有一个 data.frame ,或多或少具有以下结构:
structure(list(user = c("1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "11", "12", "13", "14", "15", "16"), group = c("G2",
"G2", "G2", "G2", "G1", "G1", "G2", "G2", "G2", "G1", "G2", "G1",
"G1", "G2", "G1", "G2"), gender = c("M", "H", "H", "M", "M",
"M", "M", "M", "M", "M", "M", "M", "H", "H", "M", "H"), level = c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L)), row.names = c(NA,
-16L), class = c("tbl_df", "tbl", "data.frame"))
我想做的是:
这样我的数据就可以是这样的:(此图片仅用于说明目的)
我尝试过
db%>%
arrange(group, gender, level)
还有
db %>%
arrange(factor(group, levels = c("G1", "G2")),
factor(gender, levels= c("M", "H")),
factor(level, levels= c(1, 2, 3, 4)))
但这些都没有给我我想要实现的目标。
任何建议将不胜感激。
没有简单的方法可以做到这一点。
尽管如此,它还是可以揭示以下方法:
attach(df)
a <- which(group == "G1" & gender == "H")
b <- which(group == "G1" & gender == "M")
c <- which(group == "G2" & gender == "H")
d <- which(group == "G2" & gender == "M")
# Filling with NAs till each group reach same length
a <- c(a, rep(NA, length(b)-length(a)))
c <- c(c, rep(NA, length(d)-length(c)))
# To interlace groups
e <- na.omit(c(rbind(a,b)))
f <- na.omit(c(rbind(c,d)))
o <- c(e,f) # final ordering
输出
df[o,]
user group gender level
13 13 G1 H 1
5 5 G1 M 1
6 6 G1 M 2
10 10 G1 M 2
12 12 G1 M 4
15 15 G1 M 3
2 2 G2 H 2
1 1 G2 M 1
3 3 G2 H 3
4 4 G2 M 4
14 14 G2 H 2
7 7 G2 M 3
16 16 G2 H 4
8 8 G2 M 4
9 9 G2 M 1
11 11 G2 M 3