在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"

我只想删除数据帧2中每行中逗号分隔的基因,这些基因位于数据帧1的列基因中,而数据帧2中的其他基因不在数据帧1中。

使用tidyverse:

library(tidyverse)
library(rebus)
#> 
#> Attaching package: 'rebus'
#> The following object is masked from 'package:stringr':
#> 
#>     regex
#> The following object is masked from 'package:ggplot2':
#> 
#>     alpha
dataframe1 <- tibble(gene = c("a", "b", "c", "d", "e", "f"))
dataframe2 <- tibble(gene = c("a,b,c,d,r,t,y","c,g,h,k,l,a,b,c,p"))
result <- str_extract_all(dataframe2$gene, rebus::or1(dataframe1$gene)) %>%
map(~ reduce(.x, str_c, sep = ','))
mutate(dataframe2, gene = result) %>% unnest(c(gene))
#> # A tibble: 2 x 1
#>   gene   
#>   <chr>  
#> 1 a,b,c,d
#> 2 c,a,b,c

创建于2021-06-28由reprex包(v2.0.0(

sapplydataframe2$gene的每一行上循环,并在strsplit之后只保留%in%dataframe$gene1的值,以获得每个逗号分隔的值。

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

使用@thelatemail中数据的tidyverse选项。

library(dplyr)
library(tidyr)
dataframe2 %>%
mutate(row =  row_number()) %>%
separate_rows(gene, sep = ',') %>%
left_join(dataframe1 %>%
mutate(gene_sub = gene), by = 'gene') %>%
group_by(row) %>%
summarise(across(c(gene, gene_sub), ~toString(na.omit(.)))) %>%
select(-row)
#  gene                      gene_sub  
#  <chr>                     <chr>     
#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

最新更新