首页 > 解决方案 > 在 2 个数据框之间选择一些值

问题描述

我有两个数据框,其中一个有一列 100 个基因,另一个数据框有一列包含 700 行,每行有几个用逗号分隔的基因,现在我不知道如何选择基因根据数据框 1 中的基因列,数据框 2 的每一行。换句话说,我希望数据框 2 的每一行中的基因位于数据框 1 的基因列中。

dataframe1:
column gene:
a
b
c
d
e
f

dataframe2:
column gene: 
row1"a,b,c,d,r,t,y"
row2"c,g,h,k,l,a,b,c,p"

我只希望删除 dataframe2 的每一行中的逗号分隔的基因,这些基因位于 dataframe1 的列基因中,而数据框 2 中的其他基因不在 dataframe1 中。

标签: r

解决方案


遍历dataframe2$genewith的每一行sapply并仅保留%in% dataframe$gene1, 之后的值strsplit以获取每个逗号分隔的值。

dataframe1 <- data.frame(gene = c("a", "b", "c", "d", "e", "f"),
                         stringsAsFactors=FALSE)
dataframe2 <- data.frame(gene = c("a,b,c,d,r,t,y", "c,g,h,k,l,a,b,c,p"),
                         stringsAsFactors=FALSE)

dataframe2$gene_sub <- sapply(
    strsplit(dataframe2$gene, ","),
    function(x) paste(x[x %in% dataframe1$gene], collapse=",")
)

dataframe2
##               gene gene_sub
##1     a,b,c,d,r,t,y  a,b,c,d
##2 c,g,h,k,l,a,b,c,p  c,a,b,c

推荐阅读