gpt4 book ai didi

基于一列重新编码数据框

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

我有一个 5845*1095(行*列)的数据框,如下所示:

 9  286593   C     C/C     C/A     A/A
9 334337 A A/A G/A A/A
9 390512 C C/C C/C C/C

c <- c("9", "286593", "C", "C/C", "C/A", "A/A")
d <- c("9", "334337", "A", "A/A", "G/A", "A/A")
e <- c("9", "390512", "C", "C/C", "C/C", "C/C")
dat <- data.frame(rbind(c,d,e))

我希望第三列中的值用于将列更改为其右侧,因此如果(每行 1)第 3 列是“C”,则第 4 列从“C/C”变为“0”,因为它有同一个字母。一个字母匹配是 "1"(可以是第一个或第二个字母),没有字母匹配是 "2"。
9 286593  C  0  1  2
9 334337 A 0 1 0
9 390512 C 0 0 0

c <- c("9", "286593", "C", "0", "1", "2")
d <- c("9", "334337", "A", "0", " 1", "0")
e <- c("9", "390512", "C", "0", "0", "0")
dat <- data.frame(rbind(c,d,e))

我有兴趣看到最好的方法来做到这一点,因为我想摆脱在 中使用嵌套 For 循环的习惯R .

最佳答案

首先你的数据:

c <-  c("9", "286593", "C", "C/C", "C/A", "A/A")
# Note: In your original data, you had a space in "G/A", which I did remove.
# If this was no mistake, we would also have to deal with the space.
d <- c("9", "334337", "A", "A/A", "G/A", "A/A")
e <- c("9", "390512", "C", "C/C", "C/C", "C/C")
dat <- data.frame(rbind(c,d,e))

现在我们生成一个包含所有可用字母的向量。
values <- c("A", "C", "G", "T")
dat$X3 <- factor(dat$X3, levels=values) # This way we just ensure that it will later on be possible to compare the reference values to our generated data.

# Generate all possible combinations of two letters
combinations <- expand.grid(f=values, s=values)
combinations <- cbind(combinations, v=with(combinations, paste(f, s, sep='/')))

主函数找到每列的每个组合的正确列,然后将其与引用列 3 进行比较。
compare <- function(col, val) {
m <- match(col, combinations$v)
2 - (combinations$f[m] == val) - (combinations$s[m] == val)
}

最后,我们使用 apply 在所有必须更改的列上运行该函数。您可能希望将 6 更改为您的实际列数。
dat[,4:6] <- apply(dat[,4:6], 2, compare, val=dat[,3])

请注意,与迄今为止的其他解决方案相比,此解决方案不使用字符串比较,而是一种纯粹基于因子水平的方法。看看哪个表现更好会很有趣。

编辑

我只是做了一些基准测试:
    test replications elapsed relative user.self sys.self user.child sys.child
1 arun 1000000 2.881 1.116 2.864 0.024 0 0
2 fabio 1000000 2.593 1.005 2.558 0.030 0 0
3 roland 1000000 2.727 1.057 2.687 0.048 0 0
5 thilo 1000000 2.581 1.000 2.540 0.036 0 0
4 tyler 1000000 2.663 1.032 2.626 0.042 0 0

这让我的版本稍微快一点。但是,差异几乎为零,因此您可能对每种方法都满意。公平地说:我没有对添加额外因子水平的部分进行基准测试。这样做也可能会排除我的版本。

关于基于一列重新编码数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17278488/

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