Calculate frequency of values spread across multiple columns in R

Viewed 81

I have a data set similar to this tibble:

  ~PatientID, ~A1, ~A2, ~B1, ~B2,
  #--|---|---|---|---
 101, "01:01", "02:01", "07:01", "51:01",
 102, "02:01", "03:01", "08:01", "51:01",
 103, "01:01", "03:01", "07:01", "08:01",
 104, "03:01", "68:01", "14:01", "08:01"
 )

They are gene types for patients. Since people have two copies of each gene, there are two columns for each gene per patient (e.g. A1 & A2). I am trying to calculate the frequency of each gene. Since the genes are spread between two columns, I am having a hard time figuring this out. Is there a way to calculate frequencies across multiple columns? My desired output would look something like this for the A gene:

A_value A_count
01:01 2
02:01 2
03:01 3
68:01 1

Would appreciate code using dplyr, since that is what I'm trying to learn!

1 Answers

We could select the columns that starts_with 'A', then reshape to 'long' format with pivot_longer and get the count

library(dplyr)
library(tidyr)
df1 %>%
     select(starts_with("A")) %>%
     pivot_longer(cols = everything(), values_to = "A_value") %>% 
     count(A_value, name = "A_count")

-output

# A tibble: 4 x 2
  A_value A_count
  <chr>     <int>
1 01:01         2
2 02:01         2
3 03:01         3
4 68:01         1

Or use table after unlisting the subset of dataset in base R

table(unlist(df1[startsWith(names(df1), "A")]))

data

df1 <- structure(list(PatientID = c(101, 102, 103, 104), A1 = c("01:01", 
"02:01", "01:01", "03:01"), A2 = c("02:01", "03:01", "03:01", 
"68:01"), B1 = c("07:01", "08:01", "07:01", "14:01"), B2 = c("51:01", 
"51:01", "08:01", "08:01")), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame"))
Related