2013-01-17 60 views
0

我有一个数据帧,看起来像这样:如何使用重塑包重塑我的数据帧?

step var1 score1 score2 
1  a 0  0 
2  b 1  1 
3  d 1  1 
4  e 0  0 
5  g 0  0 
1  b 1  1 
2  a 1  0 
3  d 1  0 
4  e 0  1 
5  f 1  1 
1  g 0  1 
2  d 1  1 
etc. 

,因为我需要相关variabeles AG(他们的成绩都在score1)与唯我想我需要schange我的数据集到这个第一步5 score2:

a b c d e f g score2_step5 
0 1  1 0  0 0 
1 1  1 0 1  1 
      1   0 
etc. 

我敢肯定的是,整形包装应该能够帮我做这份工作,但我一直没能使其工作还没有。 任何人都可以帮助我吗?提前谢谢了!

回答

2

下面是另一个版本。如果没有step = 5,则值为score2_step = 0。假设您的data.framedf

require(reshape2) 
out <- do.call(rbind, lapply(seq(1, nrow(df), by=5), function(ix) { 
    iy <- min(ix+4, nrow(df)) 
    df.b <- df[ix:iy, ] 
    tt <- dcast(df.b, 1 ~ var1, fill = 0, value.var = "score1", drop=F) 
    tt$score2_step5 <- 0 
    if (any(df.b$step == 5)) { 
     tt$score2_step5 <- df.b$score2[df.b$step == 5] 
    } 
    tt[,-1] 
})) 

> out 
    a b d e f g score2_step5 
2 0 1 1 0 0 0   0 
21 1 1 1 0 1 0   1 
22 0 0 1 0 0 0   0 
1

看起来你想要7个变量a-g和score2_step5之间的相关性 - 是否正确?首先,你将需要另一个变量。我假设step从1到5连续重复;如果没有,这将变得更加复杂。我假设你的数据被称为df。我也喜欢更新的reshape2包,所以我使用它。

df$block <- rep(1:(nrow(df)/5),each=5) 
df.molten <- melt(df,id.vars=c("var1", "step", "block"),measure.vars=c("score1")) 
df2 <- dcast(df.molten, block ~ var1) 
score2_step5 <- df$score2[df$step==5] 

,最后

cor(df2, score2_step5, use='pairwise') 

有一个在df2一个额外的列(block),您可以摆脱或忽略。

0

我在示例数据中添加了另一行,因为我的代码不工作,除非在每个块中都有第5步观察。

dat <- read.table(textConnection(" 
step var1 score1 score2 
1  a 0  0 
2  b 1  1 
3  d 1  1 
4  e 0  0 
5  g 0  0 
1  b 1  1 
2  a 1  0 
3  d 1  0 
4  e 0  1 
5  f 1  1 
1  g 0  1 
2  d 1  1 
5  a 1  0"),header=TRUE) 

像@JonathanChristensen,我提出另一个变量(I称之为rep代替block)和I制成var1成因子(由于不存在c值中的示例数据集给出我想要的占位符)。

dat <- transform(dat,var1=factor(var1,levels=letters[1:7]), 
       rep=cumsum(step==1)) 

tapply使得score1值表:

tab <- with(dat,tapply(score1,list(rep,var1),identity)) 

添加score2,一步5个值:

data.frame(tab,subset(dat,step==5,select=score2))