重塑R:拆分一列

时间:2013-09-08 18:19:18

标签: r reshape

一个非常简单的问题,但我找不到解决方案: 我有一个data.frame,如

V1 <- c("A","A","B","B","C","C")
V2 <- c("D","D","E","E","F","F")
V3 <- c(10:15)
df <- data.frame(cbind(V1,V2,V3))

即。

V1 V2 V3
A  D  10
A  D  11
B  E  12
B  E  13
C  F  14
C  F  15

我想要

V1 V2 V3.1 V3.2
A  D   10   11
B  E   12   13
C  F   14   15

我尝试重塑{stats}和reshape2

2 个答案:

答案 0 :(得分:4)

正如我所提到的,你需要的只是一个“时间”变量,你应该没事。

Mark Miller显示基本R方法,并手动创建时间变量。

这是一种自动创建时间变量的方法,以及来自“reshape2”包的dcast的等效命令:

## Creating the "time" variable. This does not depend
##  on the rows being in a particular order before
##  assigning the variables
df <- within(df, {
  A <- do.call(paste, df[1:2])
  time <- ave(A, A, FUN = seq_along)
  rm(A)
})

## This is the "reshaping" step
library(reshape2)
dcast(df, V1 + V2 ~ time, value.var = "V3")
#   V1 V2  1  2
# 1  A  D 10 11
# 2  B  E 12 13
# 3  C  F 14 15

自我提升提醒

由于此类问题已多次出现,并且由于许多数据集并不总是具有唯一ID,因此我在“splitstackshape”中将上述变体实现为名为getanID的函数“包裹。在目前的版本中,它将“时间”变量的名称硬编码为“.id”。如果您使用它,步骤将是:

library(splitstackshape)
library(reshape2)
df <- getanID(df, id.vars=c("V1", "V2"))
dcast(df, V1 + V2 ~ .id, value.var = "V3")

答案 1 :(得分:3)

V1 <- c("A","A","B","B","C","C")
V2 <- c("D","D","E","E","F","F")
V3 <- c(10:15)
time <- rep(c(1,2), 3)
df <- data.frame(V1,V2,V3,time)
df

reshape(df, idvar = c('V1','V2'), timevar='time', direction = 'wide')

  V1 V2 V3.1 V3.2
1  A  D   10   11
3  B  E   12   13
5  C  F   14   15