2016-02-09 44 views
1

我有下面的例子中数据帧,我需要重塑,但我不能够使用的重塑或转换函数做什么,我需要重塑/播数据帧 - 基于变量和多值创建新列

df 
    Testee Gender UniqueIdentifier BirthYear Graph V1 V2 V3 V4 
1 7685906  1 33448683-29373  1996  1 4 6 6 5 
2  NA  NA       NA  2 7 2 9 6 
3  NA  NA       NA  3 -3 4 -3 -1 
4 7685910  2 33444446-47897  1997  1 8 0 3 4 
5  NA  NA       NA  2 7 9 3 2 
6  NA  NA       NA  3 1 -9 0 2 

我想转置每个图(1,2和3)的V1,V2,V3和V4的行值。所以,我需要12列:Graph1.V1 Graph1.V2 Graph1.V3 Graph1.V4 Graph2.V1 Graph2.V2等,但我跟投功能

这是所需的输出

df2 
    Testee Gender UniqueIdentifier BirthYear X1.V1 X1.V2 X1.V3 X1.V4 X2.V1 X2.V2 X2.V3 X2.V4 X3.V1 X3.V2 X3.V3 X3.V4 
1 7685906  1 33448683-29373  1996  4  6  6  5  7  2  9  6 -3  4 -3 -1 
2 7685910  2 33444446-47897  1997  8  0  3  4  7  9  3  2  1 -9  0  2 

挣扎任何帮助表示赞赏!

回答

3

我们可以改变在“唯一标识符”到“NA”空白元,使用na.locf通过与lapply循环到“NA”值转换为先前的非NA元件的前4列,然后用dcastdata.table(将'data.frame'转换为'data.table'(setDT(df1))),因为它可能需要多个value.var列。

df1$UniqueIdentifier[df1$UniqueIdentifier==''] <- NA 
library(zoo) 
df1[1:4] <- lapply(df1[1:4], na.locf) 

library(data.table) 
dcast(setDT(df1), Testee+Gender+UniqueIdentifier+BirthYear~Graph, 
         value.var=c('V1', 'V2', 'V3', 'V4')) 
# Testee Gender UniqueIdentifier BirthYear V1_1 V1_2 V1_3 V2_1 V2_2 V2_3 V3_1 
#1: 7685906  1 33448683-29373  1996 4 7 -3 6 2 4 6 
#2: 7685910  2 33444446-47897  1997 8 7 1 0 9 -9 3 
#  V3_2 V3_3 V4_1 V4_2 V4_3 
# 1: 9 -3 5 6 -1 
# 2: 3 0 4 2 2 

或用na.locf后前处理,我们可以使用reshapebase R

reshape(df1, idvar=c('Testee', 'Gender', 
     'UniqueIdentifier', 'BirthYear'), 
      timevar='Graph',direction='wide') 
# Testee Gender UniqueIdentifier BirthYear V1.1 V2.1 V3.1 V4.1 V1.2 V2.2 V3.2 V4.2 V1.3 V2.3 V3.3 V4.3 
#1 7685906  1 33448683-29373  1996 4 6 6 5 7 2 9 6 -3 4 -3 -1 
#4 7685910  2 33444446-47897  1997 8 0 3 4 7 9 3 2 1 -9 0 2 
+1

完美的作品,谢谢!! –