Christina
Christina

Reputation: 85

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

Upvotes: 2

Views: 54

Answers (3)

Ben
Ben

Reputation: 30474

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

Upvotes: 2

maydin
maydin

Reputation: 3755

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

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 101678

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

Upvotes: 2

Related Questions