gpt4 book ai didi

r - 如何比较两个数据帧/表并在R中提取数据?

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

为了尝试提取下面两个数据帧之间的不匹配,我已经设法创建一个新的数据帧,在其中替换了不匹配的内容。
我现在需要的是不匹配项列表:

dfA <- structure(list(animal1 = c("AA", "TT", "AG", "CA"), animal2 = c("AA", "TB", "AG", "CA"), animal3 = c("AA", "TT", "AG", "CA")), .Names = c("animal1", "animal2", "animal3"), row.names = c("snp1", "snp2", "snp3", "snp4"), class = "data.frame")
# > dfA
# animal1 animal2 animal3
# snp1 AA AA AA
# snp2 TT TB TT
# snp3 AG AG AG
# snp4 CA CA CA
dfB <- structure(list(animal1 = c("AA", "TT", "AG", "CA"), animal2 = c("AA", "TB", "AG", "DF"), animal3 = c("AA", "TB", "AG", "DF")), .Names = c("animal1", "animal2", "animal3"), row.names = c("snp1", "snp2", "snp3", "snp4"), class = "data.frame")
#> dfB
# animal1 animal2 animal3
#snp1 AA AA AA
#snp2 TT TB TB
#snp3 AG AG AG
#snp4 CA DF DF

为了澄清不匹配,在这里将它们标记为00:
#      animal1 animal2 animal3
# snp1 AA AA AA
# snp2 TT TB 00
# snp3 AG AG AG
# snp4 CA 00 00

我需要以下输出:
structure(list(snpname = structure(c(1L, 2L, 2L), .Label = c("snp2", "snp4"), class = "factor"), animalname = structure(c(2L, 1L, 2L), .Label = c("animal2", "animal3"), class = "factor"), alleledfA = structure(c(2L, 1L, 1L), .Label = c("CA", "TT"), class = "factor"), alleledfB = structure(c(2L, 1L, 1L), .Label = c("DF", "TB"), class = "factor")), .Names = c("snpname", "animalname", "alleledfA", "alleledfB"), class = "data.frame", row.names = c(NA, -3L))
# snpname animalname alleledfA alleledfB
#1 snp2 animal3 TT TB
#2 snp4 animal2 CA DF
#3 snp4 animal3 CA DF

到目前为止,我一直在尝试从 lapply函数中提取其他数据,该函数用于将不匹配项替换为零,但没有成功。我也尝试编写ifelse函数,但没有成功。希望你们能在这里帮助我!

最终,它将针对尺寸为100K x 1000的数据集运行,因此效率高

最佳答案

这个问题带有data.table标记,因此这是我尝试使用此软件包的尝试。第一步是将行名转换为data.table不喜欢的列,然后在rbind编码后转换为长格式,并为每个数据集设置一个ID,找出存在多个唯一值的位置,然后转换回宽格式

library(data.table)  
setDT(dfA, keep.rownames = TRUE)
setDT(dfB, keep.rownames = TRUE)

dcast(melt(rbind(dfA,
dfB,
idcol = TRUE),
id = 1:2
)[,
if(uniqueN(value) > 1L) .SD,
by = .(rn, variable)],
rn + variable ~ .id)

# rn variable 1 2
# 1: snp2 animal3 TT TB
# 2: snp4 animal2 CA DF
# 3: snp4 animal3 CA DF

关于r - 如何比较两个数据帧/表并在R中提取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36592184/

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