繁体   English   中英

如何使用重塑包重塑数据框?

[英]How can I reshape my dataframe using reshape package?

我有一个看起来像这样的数据框:

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.

因为仅在第5步中我需要将variabeles ag(它们的分数在score1中)与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.

我很确定Reshape软件包应该能够帮助我完成这项工作,但是我还无法使其工作。 谁能帮我? 提前谢谢了!

这是另一个版本。 如果没有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

看来您想要变量ag和score2_step5-之间的7个相关性-正确吗? 首先,您将需要另一个变量。 我假设该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 ),您可以删除或忽略它。

我向您的示例数据添加了另一行,因为除非每个块中都没有执行第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一样,我创建了另一个变量(我将其称为rep而不是block ),并且使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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM