【问题标题】:Reshape/Cast data frame - create new columns based on variable and multiple values重塑/铸造数据框 - 基于变量和多个值创建新列
【发布时间】:2016-05-19 06:12:39
【问题描述】:

我有以下示例数据框,我需要对其进行整形,但无法使用整形或强制转换函数来做我需要做的事情

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 等,但我正在努力使用 cast 函数

这是想要的输出

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

感谢任何帮助!

【问题讨论】:

    标签: r casting reshape transpose melt


    【解决方案1】:

    我们可以将'UniqueIdentifier'中的空白元素更改为'NA',使用na.locf通过循环lapply将前4列的'NA'值转换为前一个非NA元素,然后使用来自data.tabledcast(在将'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预处理后,我们可以使用base R中的reshape

     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
    

    【讨论】:

      猜你喜欢
      • 2014-07-12
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 2019-10-08
      • 1970-01-01
      相关资源
      最近更新 更多