gpt4 book ai didi

在 R 中逐行重新排序数据帧的列

转载 作者:行者123 更新时间:2023-12-03 21:59:07 25 4
gpt4 key购买 nike

我在 R 中有一个数据框,看起来像这样:

df <- paste0(c(letters[seq( from = 1, to = 5 )]),":",round(runif(5),2)) 
df <- as.data.frame(t(df))
df2 <- paste0(c(letters[seq( from = 1, to = 5 )]),":",round(runif(5),2))
df2 <- as.data.frame(t(df2))
df3 <- paste0(c(letters[seq( from = 1, to = 5 )]),":",round(runif(5),2))
df3 <- as.data.frame(t(df3))
df <- rbind(df, setNames(sample(df2), names(df2)))
df <- rbind(df, setNames(sample(df3), names(df3)))

df


V1 V2 V3 V4 V5
1 a:0.21 b:0.49 c:0.96 d:0.95 e:0.03
2 b:0.33 c:0.25 e:0.81 d:0.94 a:0.02
3 c:0.34 e:0.26 a:0.31 d:0.55 b:0.63


冒号前的字符反射(reflect)了测量的类型,冒号后的数字反射(reflect)了测量本身。

我想对每一行进行排序,以便每种类型的度量(即冒号前的字符)都在同一列中。它应该是这样的:
      V1     V2     V3     V4     V5
1 a:0.21 b:0.49 c:0.96 d:0.95 e:0.03
2 a:0.02 b:0.33 c:0.25 d:0.94 e:0.81
3 a:0.31 b:0.63 c:0.34 d:0.55 e:0.26


或者更好:
  a    b    c    d      e
1 0.21 0.49 0.96 0.95 0.03
2 0.02 0.33 0.25 0.94 0.81
3 0.31 0.63 0.34 0.55 0.26


关于如何重新排序每一行以便冒号前的字符在给定列中相同的任何想法?

任何意见,将不胜感激!

最佳答案

您可以使用 substr .

res <- as.data.frame(t(apply(df, 1, function(x) x[order(substr(x, 1, 1))])))
res
# V1 V2 V3 V4 V5
# 1 a:0.96 b:0.94 c:0.34 d:0.85 e:0.2
# 2 a:0.84 b:0.32 c:0.78 d:0.67 e:0.32
# 3 a:0.59 b:0.82 c:0.79 d:0.7 e:0.2

或者,去掉后缀并转换为数字:
res <- as.data.frame(t(apply(df, 1, function(x) 
as.numeric(as.character(substring(x, 3)[order(substr(x, 1, 1))])))))
res
# V1 V2 V3 V4 V5
# 1 0.96 0.94 0.34 0.85 0.20
# 2 0.84 0.32 0.78 0.67 0.32
# 3 0.59 0.82 0.79 0.70 0.20

str(res)
# 'data.frame': 3 obs. of 5 variables:
# $ V1: num 0.96 0.84 0.59
# $ V2: num 0.94 0.32 0.82
# $ V3: num 0.34 0.78 0.79
# $ V4: num 0.85 0.67 0.7
# $ V5: num 0.2 0.32 0.2

或者,使用正则表达式:
as.data.frame(t(apply(df2, 1, function(x) {
g1 <- gsub(x, pattern="(\\w+\\:).*", r="\\1")
g2 <- gsub(x, pattern="\\w+\\:(.*)", r="\\1")
as.numeric(as.character(g2[order(g1)]))
})))
# V1 V2 V3 V4 V5
# 1 0.96 0.94 0.34 0.85 0.2
# 2 0.84 0.32 0.78 0.67 0.32
# 3 0.59 0.82 0.79 0.7 0.2

df2 的数据
df2 <- df
df2[] <- lapply(df2, function(x) as.character(x))
df2[2, ] <- c("cc:0.78", "e:0.32", "dd:0.67", "a:0.84", "bb:0.32")
df2
# V1 V2 V3 V4 V5
# 1 a:0.96 b:0.94 c:0.34 d:0.85 e:0.2
# 2 cc:0.78 e:0.32 dd:0.67 a:0.84 bb:0.32
# 3 d:0.7 b:0.82 e:0.2 a:0.59 c:0.79

关于在 R 中逐行重新排序数据帧的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60664813/

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