Function to generate frequency table of individual values given a data frame with a column of comma-separated values in R

Viewed 41

Sample data

df <- tibble(x = c("c('gene1', 'gene2', 'gene2', 'gene3')",
                   "c('gene3', 'gene4', 'gene5'"))
# A tibble: 2 x 1
  x                                    
  <chr>                                
1 c('gene1', 'gene2', 'gene2', 'gene3')
2 c('gene3', 'gene4', 'gene5'

Yes, each value in this column x is indeed a paste of c(). The original algorithm used outputs a dataframe containing a column of c() strings of gene names.

Desired Output

# A tibble: 5 x 2
  gene   freq
  <chr> <dbl>
1 gene1     1
2 gene2     2
3 gene3     2
4 gene4     1
5 gene5     1

Fast or tidyverse-based solutions would be welcomed!

1 Answers

It may be better to split the column 'x' with separate_rows. By default the sep will use the , as split, then we filter out the "c" and blank "" elements before doing the count

library(dplyr)
library(tidyr)
df %>%
     separate_rows(x) %>% 
     filter(!x %in% c("c", "")) %>%
     count(gene = x, name = 'freq')

-output

# A tibble: 5 x 2
#  gene   freq
#* <chr> <int>
#1 gene1     1
#2 gene2     2
#3 gene3     2
#4 gene4     1
#5 gene5     1
Related