假设 M
具有以下结构:-
> dput(head(M))
structure(list(SV = structure(c(38L, 21L, 24L, 20L, 54L, 45L), .Label = c("X1 X2 X3",
"X1 X2 X3 X10 X6 X9", "X1 X2 X3 X10 X8 X9", "X1 X2 X3 X10 X9 X8",
"X1 X2 X3 X4", "X1 X2 X3 X4 X9 X7", "X1 X2 X3 X5", "X1 X2 X3 X5 X10",
"X1 X2 X3 X5 X6 X4", "X1 X2 X3 X5 X9", "X1 X2 X3 X6", "X1 X2 X3 X6 X7",
"X1 X2 X3 X7", "X1 X2 X3 X7 X8 X10", "X1 X2 X3 X8", "X1 X2 X3 X8 X4",
"X1 X2 X3 X8 X9 X10 X7", "X1 X2 X3 X9", "X1 X2 X3 X9 X10", "X1 X2 X3 X9 X5",
"X2 X1 X3", "X2 X1 X3 X10", "X2 X1 X3 X10 X5", "X2 X1 X3 X10 X9",
"X2 X1 X3 X4", "X2 X1 X3 X4 X10", "X2 X1 X3 X4 X6", "X2 X1 X3 X4 X8",
"X2 X1 X3 X5 X10 X4", "X2 X1 X3 X5 X4", "X2 X1 X3 X5 X7", "X2 X1 X3 X6",
"X2 X1 X3 X6 X5 X7", "X2 X1 X3 X6 X8", "X2 X1 X3 X6 X8 X9", "X2 X1 X3 X7",
"X2 X1 X3 X7 X10", "X2 X1 X3 X7 X4", "X2 X1 X3 X7 X5", "X2 X1 X3 X7 X9 X5",
"X2 X1 X3 X8", "X2 X1 X3 X8 X10 X4", "X2 X1 X3 X8 X10 X5 X9",
"X2 X1 X3 X8 X6", "X2 X1 X3 X9", "X2 X1 X3 X9 X5", "X2 X1 X3 X9 X5 X4",
"X2 X1 X3 X9 X6 X7 X10", "X2 X1 X3 X9 X7", "X2 X3 X1 X5 X6",
"X2 X3 X1 X8", "X3 X1 X2", "X3 X2 X1", "X3 X2 X1 X4"), class = "factor")), row.names = c(NA,
6L), class = "data.frame")
可以看出,在某些行中它们是不连续的。我需要按顺序出现在这个顺序
X1 X2 X3 X4 X5 X6 X7
中。如何重新排列
M
的行 最佳答案
您需要拆分,剥离数字和顺序,即
M$SV <- sapply(M$SV, function(i){i1 <- strsplit(as.character(i), ' ')[[1]];
i2 <- i1[order(as.numeric(gsub('\\D+', '', i1)))];
paste(i2, collapse = ' ')})
这使,
关于在矩阵的一行中重新排列字符向量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60170773/