gpt4 book ai didi

在矩阵的一行中重新排列字符向量

转载 作者:行者123 更新时间:2023-12-04 11:42:27 25 4
gpt4 key购买 nike

假设 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 = ' ')})

这给出了,

               SV
1 X1 X2 X3 X4 X7
2 X1 X2 X3
3 X1 X2 X3 X9 X10
4 X1 X2 X3 X5 X9
5 X1 X2 X3 X4
6 X1 X2 X3 X9

关于在矩阵的一行中重新排列字符向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60170773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com