2012-03-06 78 views
2

所以 - 我用那种有这些团体通过一个ID索引的重复观察的DF工作,像这样:如何在R中重新塑造这些数据?

id | x1 | x2 | y1 | y2 
1 a b c 2 
1 a b d 3 
1 a b e 4 
2 ... 
2 ... 
... 

即每个组内的所有变量都相同,除Y1和Y2 (一般来说,y2'修改'y1。)我列出的所有这些变量都是因素。我想要做的就是把这些群体中的每一个到的东西,类似于以下内容:

id | x1 | x2 | y1' | y2' | y3' 
1 a b c-2 d-3 e-4 
2 ... 

,其中Y1的(Y1贷)是Y1和Y2的相邻值的级联,用破折号在之间。然而,y1的数量不同于id-group到id-group,但我很乐意看到一个非常宽泛的数据框架,它允许这些额外的解决方案。无论如何,我已经(非常徒劳地,我必须承认)试图融合并用reshape2投射这些数据,但在这一点上,我不确定我是不是正在做这个权利,或者这个包不是一个适合我在这里要做的事情。任何意见将不胜感激 - 谢谢!

回答

1

如果我理解正确的问题,在这里是一种与plyr做到这一点:

foo <- read.table(textConnection("id x1 x2 y1 y2 
1 a b c 2 
1 a b d 3 
1 a b e 4"),header=TRUE) 


library("plyr") 

ddply(foo,.(x1,x2),with,{ 
     res <- data.frame(
      id = id[1], 
      x1 = x1[1], 
      x2 = x2[1]) 
     for (i in 1:length(y1)) 
     { 
      res[[paste("y",i,sep="")]] <- paste(y1,y2,sep="-")[i] 
     } 
     return(res) 
     } 
    ) 

这将返回:

id x1 x2 y1 y2 y3 
1 1 a b c-2 d-3 e-4 
1

我看到萨沙的回答,我想我会努力扩展它更长的数据集。我不认为这会给你想要的结果,但我不确定。我不清楚你想要做什么。所以这是我试图这样做,你以后在做什么,但我不完全知道那是什么:

foo <- read.table(textConnection("id x1 x2 y1 y2 
1 a b c 2 
1 a b d 3 
1 a b e 4 
2 a b f 2 
2 a b g 3 
2 a b h 4"),header=TRUE) 


new <- transform(foo, time.var=paste(id, x1, x2, sep=""), 
    y1=paste(y1, y2, sep="-"))[, -5] 

new <- data.frame(unique(foo[, 1:3]), t(unstack(new[, 4:5]))) 
names(new)[4:6] <- paste("y", 1:3, sep="") 
new 

虽然我认为萨沙的回答工作和我一样,如果你把ID与x1和x2(我猜这可能是更普及):

ddply(foo,.(id, x1,x2),with,{ 
     res <- data.frame(
      id = id[1], 
      x1 = x1[1], 
      x2 = x2[1]) 
     for (i in 1:length(y1)) 
     { 
      res[[paste("y",i,sep="")]] <- paste(y1,y2,sep="-")[i] 
     } 
     return(res) 
     } 
    ) 

编辑:此解决方案可能会更普及:

new <- transform(foo, y=paste(y1, y2, sep="-"), stringsAsFactors=FALSE) 
aggregate(y~id+x1+x2, new, c) 
0

是的,这就是重塑包为f要么。首先准备数据:

foo <- transform(foo, 
       y = paste(y1,y2, sep = "-"), 
       ix = unlist(tapply(id, id, function(gr) 1:length(gr)))) 

然后继续你的变换:

mfoo <- melt(foo, measure.vars = "y") 
cast(mfoo, id + x1 + x2 ~ variable + ix) 

应该给

id x1 x2 y_1 y_2 y_3 
1 1 a b c-2 d-3 e-4 
2 2 a b f-2 h-4 <NA> 

与数据集

foo <- read.table(textConnection("id x1 x2 y1 y2 
1 a b c 2 
1 a b d 3 
1 a b e 4 
2 a b f 2 
2 a b g 3"),header=TRUE) 

[编辑:这是重塑,重塑你应该使用dcast而不是cast]

+0

谁降级,应该融化和烤过:) – VitoshKa 2012-03-07 19:57:59