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

Column bind frequency table

I have a frequency table that has different column numbers. I am using the following code but it is not resulting in accurate results.

data_cbind <- cbind(table_45_1,table_45_3,table_45_6,table_45_12) 

head(table_45_1)
 1  2  3 
30  4  1 

head(table_45_3)
 1  2  3  4 
10  8  1  1 

head(table_45_6)
 1  2 
 12  5
head(table_45_12)
 1   
 1  

I want to organize the data as follows:
enter image description here

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 :

You can create a list of tables, then stack them, and use Reduce to merge them altogether:

#Mock data
tab1 <- table(mtcars$vs)
tab2 <- table(mtcars$cyl)
tab3 <- table(mtcars$gear)

lapply(mget(ls(pat = "^tab")), stack) |>
  Reduce(f = \(x, y) merge(x, y, by = "ind", all = TRUE))

To get a nicer output, you can even use as.data.frame.table instead of stack which has a responseName argument (see as.data.frame(tab1, responseName = "cyl)).

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