也许这是一个非常天真的问题,但我无法弄清楚
我有这样的数据
df<- structure(list(nm1 = structure(c(3L, 4L, 2L, 1L), .Label = c("gete",
"heyet", "heyt", "jeur"), class = "factor"), nm2 = structure(c(3L,
4L, 2L, 1L), .Label = c("gei", "gsfst", "hde", "hsge"), class = "factor"),
a1 = c(3L, 1L, 1032L, 617L), a2 = c(4L, 1L, 540L, 663L),
h3 = c(5L, 5L, 1411L, 1217L), y1 = c(1L, 1L, 1764L, 972L),
u1 = c(3L, 1L, 913L, 396L), i1 = c(0L, 1L, 142L, 156L), t1 = c(1L,
3L, 811L, 811L), i9 = c(0L, 1L, 653L, 1010L)), .Names = c("nm1",
"nm2", "a1", "a2", "h3", "y1", "u1", "i1", "t1", "i9"), class = "data.frame", row.names = c(NA,
-4L))
我想基于一行(第3行)对所有内容进行排序
如果我这样做
t(apply(df[,-(1:2)], 1, sort))
它将对所有内容进行排序
如何将它们排成一行?
当列名称奇怪时,解决方案不起作用,如下面的示例
df2<- structure(list(name1 = structure(c(2L, 1L), .Label = c("KILA",
"KKIK"), class = "factor"), name2 = structure(1:2, .Label = c("BIN",
"BINA"), class = "factor"), X4932NMU = c(1033L, 846L), X4931NMU = c(1035L,
847L), X4928NMU = c(1053L, 143L), X4927NMU = c(13255L, 1517L),
X4926NMU = c(1332L, 194L), X4097NMU = c(1351L, 231L), X2572NMU = c(13542L,
253L), X2571NMU = c(1441L, 272L), X5222NMU = c(14691L, 322L
), X4213NMU = c(1738L, 322L), X2638NMU = c(1742L, 338L)), .Names = c("name1",
"name2", "X4932NMU", "X4931NMU", "X4928NMU", "X4927NMU", "X4926NMU",
"X4097NMU", "X2572NMU", "X2571NMU", "X5222NMU", "X4213NMU", "X2638NMU"
), class = "data.frame", row.names = c(NA, -2L))
例如
ix <- 1:2
o <- order(df2[1, -ix])
cbind(df2[ix], df2[-ix][o])
或
newdata <- df2[, c(1:2, order(df2[1, 3:ncol(df2) ]) + 2)]
答案 0 :(得分:0)
您可以使用:
newdata <- df[, c(1:2, order(df[3, 3:ncol(df) ]) + 2)]
结果:
> newdata
nm1 nm2 i1 a2 i9 t1 u1 a1 h3 y1
1 heyt hde 0 4 0 1 3 3 5 1
2 jeur hsge 1 1 1 3 1 1 5 1
3 heyet gsfst 142 540 653 811 913 1032 1411 1764
4 gete gei 156 663 1010 811 396 617 1217 972
说明:
我们根据第3至第10列和第3行进行排序
order(df[3, 3:ncol(df) ])
这会产生所需的索引
[1] 6 2 8 7 5 1 3 4
接下来,我们需要在索引中添加“2”以使它们与原始数据框架兼容,并排除与名称对应的列。
order(df[3, 3:ncol(df) ]) + 2
[1] 8 4 10 9 7 3 5 6
答案 1 :(得分:0)
创建o
,除第1列和第2列之外的第3行排序的索引。然后应用于df
除了第1列和第2列,并在第1列和第2列之前添加。
ix <- 1:2
o <- order(df[3, -ix])
cbind(df[ix], df[-ix][o])
,并提供:
nm1 nm2 i1 a2 i9 t1 u1 a1 h3 y1
1 heyt hde 0 4 0 1 3 3 5 1
2 jeur hsge 1 1 1 3 1 1 5 1
3 heyet gsfst 142 540 653 811 913 1032 1411 1764
4 gete gei 156 663 1010 811 396 617 1217 972
回应评论:
names(df)[3:5] <- c("0047NMU", "125NMU", "457NMU")
o <- order(df[3, -ix])
cbind(df[ix], df[-ix][, o])
,并提供:
nm1 nm2 i1 125NMU i9 t1 u1 0047NMU 457NMU y1
1 heyt hde 0 4 0 1 3 3 5 1
2 jeur hsge 1 1 1 3 1 1 5 1
3 heyet gsfst 142 540 653 811 913 1032 1411 1764
4 gete gei 156 663 1010 811 396 617 1217 972
使用df2
和第1行进行排序,我们得到了这个:
ix <- 1:2; o <- order(df2[1, -ix]); cbind(df2[ix], df2[-ix][o])
,并提供:
name1 name2 X4932NMU X4931NMU X4928NMU X4926NMU X4097NMU X2571NMU X4213NMU
1 KKIK BIN 1033 1035 1053 1332 1351 1441 1738
2 KILA BINA 846 847 143 194 231 272 322
X2638NMU X4927NMU X2572NMU X5222NMU
1 1742 13255 13542 14691
2 338 1517 253 322