gpt4 book ai didi

在 R 中的相同列中重新排列相同类型的数据值

转载 作者:行者123 更新时间:2023-12-01 13:13:41 25 4
gpt4 key购买 nike

我的数据是这样的:

df <- structure(list(X1 = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L), .Label = c("16S", "M"), class = "factor"), X2 = structure(c(1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("M", "T1", "T2",
"T3", "T4"), class = "factor"), X3 = structure(c(8L, 8L, 8L,
8L, 8L, 1L, 1L, 1L, 1L), .Label = c("R1", "R2", "R3", "R4", "T1",
"T2", "T3", "T4"), class = "factor"), X4 = structure(c(4L, 4L,
4L, 4L, 4L, 5L, 5L, 6L, 6L), .Label = c("R1", "R2", "R3", "R4",
"S1", "S2", "S3"), class = "factor"), X5 = structure(c(2L, 3L,
3L, 4L, 4L, 1L, 1L, 1L, 1L), .Label = c("16S", "S1", "S2", "S3"
), class = "factor")), row.names = 92:100, class = "data.frame")

我想将所有以 M 开头的值放在一列中,将 T 放在另一列中;值在一列中以 S 开头,在另一列中以 S 结尾,依此类推(保持行号不变)。我怎样才能在 R 中做到这一点?

预期结果:

X1 X2 X3 X4  X5
92 16S M T4 R4 S1
93 16S M T4 R4 S2
94 16S M T4 R4 S2
95 16S M T4 R4 S3
96 16S M T4 R4 S3
97 16S M T1 R1 S1
98 16S M T1 R1 S1
99 16S M T1 R1 S2
100 16S M T1 R1 S2

最佳答案

一个选项是按行排序

df[] <- t(apply(df, 1, sort))
df
# X1 X2 X3 X4 X5
#92 16S M R4 S1 T4
#93 16S M R4 S2 T4
#94 16S M R4 S2 T4
#95 16S M R4 S3 T4
#96 16S M R4 S3 T4
#97 16S M R1 S1 T1
#98 16S M R1 S1 T1
#99 16S M R1 S2 T1
#100 16S M R1 S2 T1

关于在 R 中的相同列中重新排列相同类型的数据值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57980806/

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