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

前端 未结 3 1155
清酒与你
清酒与你 2020-12-03 19:58

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 facto

3条回答
  •  鱼传尺愫
    2020-12-03 20:25

    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
    

提交回复
热议问题