Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stack only some columns in a data frame?

Tags:

r

reshape

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".

like image 751
saffsd Avatar asked Dec 16 '22 14:12

saffsd


2 Answers

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
like image 86
thelatemail Avatar answered Dec 27 '22 13:12

thelatemail


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
like image 22
agstudy Avatar answered Dec 27 '22 13:12

agstudy