简体   繁体   中英

Keep rows in dataframe containing the SAME value in one column in R

Consider the following dataframe:

Gene <- c("PNKD;TMBIM1", "PNKD", "PKHD1", "PKHD1", "SCN1A", "RBMX", "RBMX", "MUC4", "CASKIN;TRAF7", "CASKIN", "LIFR")
Score <- c(0.9, 0.2, 0.5, 0.6, 0.1, 0.985, 0.238, 0.65, 0.9, 0.66, 0.6)
df <- data.frame(Gene, Score)
df

I would like to select the rows in this dataframe in column "Gene" that contain the same string. I would like the following output:

Gene <- c("PNKD;TMBIM1", "PNKD", "PKHD1", "PKHD1", "RBMX", "RBMX","CASKIN;TRAF7", "CASKIN")
Score <- c(0.9, 0.2, 0.5, 0.6, 0.985, 0.238, 0.65, 0.9)
df <- data.frame(Gene, Score)

df

Do you mean something like below

subset(
  df,
  grepl(
    paste0(subset(data.frame(table(unlist(strsplit(Gene, ";")))), Freq > 1)$Var1, collapse = "|"),
    Gene
  )
)

which gives

           Gene Score
1   PNKD;TMBIM1 0.900
2          PNKD 0.200
3         PKHD1 0.500
4         PKHD1 0.600
6          RBMX 0.985
7          RBMX 0.238
9  CASKIN;TRAF7 0.900
10       CASKIN 0.660

It is not the best way I guess to handle but with BaseR ,

map <- unique(df[colSums(sapply(df[,1], function(x) grepl(x,df[,1])))>1,1])

do.call(rbind,lapply(map,function(x) df[grepl(x,df[,1]),]))

gives,

           Gene Score
1   PNKD;TMBIM1 0.900
2          PNKD 0.200
3         PKHD1 0.500
4         PKHD1 0.600
6          RBMX 0.985
7          RBMX 0.238
9  CASKIN;TRAF7 0.900
10       CASKIN 0.660

With tidyverse you can do the following after numbering the rows:

library(tidyverse)

df$gene_num = seq.int(nrow(df))

df_keep <- df %>%
  separate_rows(Gene, sep = ";") %>%
  group_by(Gene) %>%
  filter(n() > 1) %>%
  pull(gene_num)

df[df_keep, c("Gene", "Score")]

Output

           Gene Score
1   PNKD;TMBIM1 0.900
2          PNKD 0.200
3         PKHD1 0.500
4         PKHD1 0.600
6          RBMX 0.985
7          RBMX 0.238
9  CASKIN;TRAF7 0.900
10       CASKIN 0.660

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM