5

我遇到了一张频率表。今天很重要,我不得不扩展为原始值的数据框。我能够做到,但想知道是否有更快的方法使用 reshape 包或 data.table?

原始表格如下所示:

   i1 i2 i3 i4  m  f
1   0  0  0  0 22 29
2   1  0  0  0 30 50
3   0  1  0  0 13 15
4   0  0  1  0  1  6
5   1  1  0  0 24 67
6   1  0  1  0  5 12
7   0  1  1  0  1  2
8   1  1  1  0 10 22
9   0  0  0  1 10  7
10  1  0  0  1 27 30
11  0  1  0  1 14  4
12  0  0  1  1  1  0
13  1  1  0  1 54 63
14  1  0  1  1  8 10
15  0  1  1  1  8  6
16  1  1  1  1 57 51

这是使用 dput 轻松获取数据的示例:

dat <- structure(list(i1 = c(0L, 1L, 0L, 0L, 1L, 1L, 0L, 1L, 0L, 1L, 
0L, 0L, 1L, 1L, 0L, 1L), i2 = c(0L, 0L, 1L, 0L, 1L, 0L, 1L, 1L, 
0L, 0L, 1L, 0L, 1L, 0L, 1L, 1L), i3 = c(0L, 0L, 0L, 1L, 0L, 1L, 
1L, 1L, 0L, 0L, 0L, 1L, 0L, 1L, 1L, 1L), i4 = c(0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), m = c(22L, 30L, 
13L, 1L, 24L, 5L, 1L, 10L, 10L, 27L, 14L, 1L, 54L, 8L, 8L, 57L
), f = c(29L, 50L, 15L, 6L, 67L, 12L, 2L, 22L, 7L, 30L, 4L, 0L, 
63L, 10L, 6L, 51L)), .Names = c("i1", "i2", "i3", "i4", "m", 
"f"), class = "data.frame", row.names = c(NA, -16L))

我重塑数据的方法(有更快的方法吗?):

#step 1: method 1 (in this case binding and stacking uses less code than reshape)
dat2 <- data.frame(rbind(dat[,1:4], dat[, 1:4]), 
    sex = rep(c('m', 'f'), each=16),
    n = c(dat$m, dat$f))
dat2

#step 1: method 2    
dat3 <- reshape(dat, direction = "long", idvar = 1:4,
    varying = list(c("m", "f")),
    v.names = c("n"),
    timevar = "sex",
    times = c("m", "f"))
    rownames(dat3) <- 1:nrow(dat3)
    dat3 <- data.frame(dat3)
    dat3$sex <- as.factor(dat3$sex)

all.equal(dat3, dat2) #just to show both method 1 and 2 give the same data frame

#step 2
dat4 <- dat2[rep(seq_len(nrow(dat2)), dat2$n), 1:5]
rownames(dat4) <- 1:nrow(dat4)
dat4

我认为这是一个常见问题,因为当您想从文章中获取表格并复制它时,它需要一些拆包。我发现自己越来越多地这样做,并希望确保自己有效率。

4

4 回答 4

7

这是一个单线。

dat2 <- ddply(dat, 1:4, summarize, sex = c(rep('m', m), rep('f', f)))
于 2012-03-30T01:48:16.653 回答
5

这是一个基本的 R 单线。

dat2 <- cbind(dat[c(rep(1:nrow(dat), dat$m), rep(1:nrow(dat), dat$f)),1:4],
              sex=c(rep("m",sum(dat$m)), rep("f", sum(dat$f))))

或者,更笼统地说:

d1 <- dat[,1:4]
d2 <- as.matrix(dat[,5:6])
dat2 <- cbind(d1[rep(rep(1:nrow(dat), ncol(d2)), d2),], 
              sex=rep(colnames(d2), colSums(d2)))
于 2012-03-30T02:24:30.170 回答
3

鉴于没有人发布data.table解决方案(如原始问题中所建议)

library(data.table)
DT <- as.data.table(dat)   
DT[,list(sex = rep(c('m','f'),c(m,f))), by=  list(i1,i2,i3,i4)]

或者,更简洁

DT[,list(sex = rep(c('m','f'),c(m,f))), by=  'i1,i2,i3,i4']
于 2012-10-03T04:31:17.517 回答
2

我将melt用于第一步和ddply第二步。

library(reshape2)
library(plyr)
d <- ddply( 
  melt(dat, id.vars=c("i1","i2","i3","i4"), variable.name="sex"), 
  c("i1","i2","i3","i4","sex"), 
  summarize, 
  id=rep(1,value) 
)
d$id <- cumsum(d$id)
于 2012-03-30T01:26:38.623 回答