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:
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)]