Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a table function on a dataframe based on a series of subsets?

I have these many datasets : df as the main data frame (but let’s imagine all of them as very big datasets)

df = data.frame(x = seq(1,20,2),
y = c('a','a','b','c','a','a','b','c','a','a'),
z = c('d','e','e','d','f','e','e','d','e','f') )

g = data.frame(xx = c(2,3,4,5,7,8,9) )

h = data.frame(xx = c(3,5,7,8,9) )

i = data.frame(xx = c(2,3,6,8) )

j = data.frame(xx = c(1,3,6) )

And I wish to make a group of tables of frequency to the y column of df using the xx of each other dataframe each time (xx is used to subset df).

And then making a group of tables of frequency to the Z column of df using the xx of each other dataframe each time (xx is used to subset df).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We could place the datasets in a list (dplyr::lst– returns a named list), loop over the list with map, subset the main dataset based on the ‘x’ column or do a inner_join and get the frequency count

library(dplyr)
library(purrr)
map(lst(g, h, i,j), 
   ~ inner_join(df, .x, by = c("x" = "xx")) %>%      
       count(y, name = 'Count'))

-output

$g
  y Count
1 a     2
2 b     1
3 c     1

$h
  y Count
1 a     2
2 b     1
3 c     1

$i
  y Count
1 a     1

$j
  y Count
1 a     2

Or in base R

lapply(list(g = g, h = h, i = i, j = j),
  \(dat) subset(df, x %in% dat$xx, select = y ) |>
      table())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading