I have some data in a data frame in the following form:
A B C V1 V2 V3
1 1 1 x y z
1 1 2 a b c
...
Where A,B,C are factors, and the combination A,B,C is unique for each row.
I need to convert some of the columns into factors, to achieve a form like:
A B C V val
1 1 1 V1 x
1 1 1 V2 y
1 1 1 V3 z
1 1 2 V1 a
1 1 2 V2 b
1 1 2 V2 c
...
This seems to relate to both stack and the inverse of xtabs, but I don't see how to specify that only certain columns should be "stacked".
And before @AnandaMahto gets here and offers his base reshape
solution, here's my attempt:
dat <- read.table(text = 'A B C V1 V2 V3
1 1 1 x y z
1 1 2 a b c',header= T)
expandvars <- c("V1","V2","V3")
datreshape <- reshape(dat,
idvar=c("A","B","C"),
varying=list(expandvars),
v.names=c("val"),
times=expandvars,
direction="long")
> datreshape
A B C time val
1.1.1.V1 1 1 1 V1 x
1.1.2.V1 1 1 2 V1 a
1.1.1.V2 1 1 1 V2 y
1.1.2.V2 1 1 2 V2 b
1.1.1.V3 1 1 1 V3 z
1.1.2.V3 1 1 2 V3 c
Using reshape2
package
dat <- read.table(text = 'A B C V1 V2 V3
1 1 1 x y z
1 1 2 a b c',header= T)
library(reshape2)
melt(dat,id.vars = c('A','B','C'))
A B C variable value
1 1 1 1 V1 x
2 1 1 2 V1 a
3 1 1 1 V2 y
4 1 1 2 V2 b
5 1 1 1 V3 z
6 1 1 2 V3 c
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