将数据框中的列重新对齐到多个列中

时间:2012-09-16 23:56:47

标签: r

我正在尝试更改数据框列(var3,在下面的示例中),其中包含另一个变量(names的因子级别的多个值,在下面的示例中)。我希望将var3拆分为单独的列,每个值对应一列,以便names中的因子级别不重复。我的其他变量(var1var2)会在必要时重复,以便为var3提供空间。

这是我的数据类型:

df1 <- structure(list(name = structure(c(2L, 4L, 4L, 4L, 3L, 5L, 5L, 
1L), .Label = c("fifth", "first", "fourth", "second", "third"
), class = "factor"), var1 = c(90L, 84L, 84L, 84L, 18L, 22L, 
22L, 36L), var2 = c(301L, 336L, 336L, 336L, 412L, 296L, 296L, 
357L), var3 = c(-0.582075925, -1.108889624, -1.014962009, -0.162309524, 
-0.282309524, 0.563055819, -0.232075925, -0.773353424)), .Names = c("name", 
"var1", "var2", "var3"), class = "data.frame", row.names = c(NA, -8L))

这就是我想要的:

df2 <- structure(list(name = structure(c(2L, 4L, 3L, 5L, 1L), .Label = c("fifth", 
"first", "fourth", "second", "third"), class = "factor"), var1 = c(90L, 
84L, 18L, 22L, 36L), var2 = c(301L, 336L, 412L, 296L, 357L), 
var3 = c(-0.582075925, -1.108889624, -0.282309524, 0.563055819, 
-0.773353424), var3.2 = c(NA, -1.014962009, NA, -0.232075925, 
NA), var3.3 = c(NA, -0.162309524, NA, NA, NA)), .Names = c("name", "var1", 
"var2", "var3", "var3.2", "var3.3"), class = "data.frame", row.names = c(NA, -5L))

我看过reshapeddply,但无法让他们给我这个输出。

2 个答案:

答案 0 :(得分:0)

ddply(df1, .(name), function(x) {
    var3 <- data.frame(rbind(unique(x$var3)))
    names(var3) <- paste0("var3.", 1:length(var3))
    return(data.frame(name = unique(x$name), var1 = unique(x$var1), 
    var2 = unique(x$var2), var3))
    })

 name var1 var2     var3.1     var3.2     var3.3
1  fifth   36  357 -0.7733534         NA         NA
2  first   90  301 -0.5820759         NA         NA
3 fourth   18  412 -0.2823095         NA         NA
4 second   84  336 -1.1088896 -1.0149620 -0.1623095
5  third   22  296  0.5630558 -0.2320759         NA

如果您希望var1var2也包含多个值,则可以修改此功能。

答案 1 :(得分:0)

这是一个基本解决方案:

> df1$seqnam <- ave(as.character(df1$name), df1$name, FUN=seq)  # creates a "time" index 
> reshape(df1, direction="wide", timevar="seqnam",  idvar=c("name", "var1", "var2") )
    name var1 var2     var3.1     var3.2     var3.3
1  first   90  301 -0.5820759         NA         NA
2 second   84  336 -1.1088896 -1.0149620 -0.1623095
5 fourth   18  412 -0.2823095         NA         NA
6  third   22  296  0.5630558 -0.2320759         NA
8  fifth   36  357 -0.7733534         NA         NA