Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Collapse" multiple columns into two columns using column name as ID

Tags:

dataframe

r

In R, I'm trying to collapse multiple columns of a data frame into two columns, with the column names from the first data frame being copied into their own column in the resulting data frame. For instance, I have the following data frame df :

A     B     C     D
1     2     3     4
5     6     7     8

And I'm trying to get this output, which is helpful when performing ANOVA tests:

 DV     IV
 A      1
 A      5
 B      2
 B      6
 C      3
 C      7
 D      4
 D      8

I've been going about this manually by declaring new data frame like so:

 df2 <- data.frame("DV" = c(rep("A", 2), rep("B", 2), rep("C", 2), rep("D", 2)),
             "IV" = c(df$A, df$B, df$C, df$D))

I suspect aggregate() or melt() could do this more efficiently, but I'm lost in the syntax. Thanks in advance!

like image 463
cangers Avatar asked Dec 08 '22 04:12

cangers


1 Answers

You can use melt from reshape2 package

library(reshape2)
melt(df, variable.name = "DV", value.name = "IV")

  DV IV
1  A  1
2  A  5
3  B  2
4  B  6
5  C  3
6  C  7
7  D  4
8  D  8
like image 93
ExperimenteR Avatar answered Jan 19 '23 01:01

ExperimenteR