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

Combine two columns with a grouping variable (in R)

I have a dataset df and I’m trying to append the values of one column beneath another, while also taking the grouping variable (‘value’) into consideration. Is there a straightforward solution for this?

I’ve searched for a solution but haven’t found a simple one for this problem.

Here’s an example dataset:

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

df <- data.frame( value =c(0, 0, 1, 1, 2, 2), ind_1 =c("AA", "BD", "WR", "DH", "AE", "SG"), ind_2 =c("DE", "DE", "BH", "BH", "EE", "EE"))

This is how it should look in the end:

df_result <- data.frame( value =c(0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2), ind =c("AA", "BD", "DE", "DE", "WR", "DH", "BH", "BH","AE", "SG" , "EE", "EE"))

>Solution :

Here’s a solution with data.table:

library(data.table)

setDT(df)
df_result <- rbind(df[, list(value, ind=ind_1)], df[, list(value, ind=ind_2)])

If the order of the values is important, you can sort like this

df_result[order(value)]
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