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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With