转换列中的行

时间:2017-06-10 12:20:02

标签: r dataframe

我有以下数据框:

Application Type    Value   Date
     X       A      323   15/04/2017
     X       B     65306  15/04/2017
     Y       A      454   15/04/2017
     X       C     53734  16/04/2017
     Y       A      208   16/04/2017
     Y       B     46689  16/04/2017
     X       B    1399283 17/04/2017

如何将行数据转换为列,如下所示:

Application Type    15/04/2017  16/04/2017  17/04/2017
     X        A        323      
     X        B       65306     
     X        C                   53734 
     Y        A        454         208  
     Y        B                   46689 
     X        B                              1399283

谢谢!

1 个答案:

答案 0 :(得分:0)

我们可以将dcastdrop = FALSE

一起使用
library(data.table)
dcast(setDT(df1), Application + Type ~Date, value.var = "Value", drop = FALSE)
#   Application Type 15/04/2017 16/04/2017 17/04/2017
#1:           X    A        323         NA         NA
#2:           X    B      65306         NA    1399283
#3:           X    C         NA      53734         NA
#4:           Y    A        454        208         NA
#5:           Y    B         NA      46689         NA
#6:           Y    C         NA         NA         NA

tidyverse

library(tidyverse)
df1 %>%
    spread(Date, Value, drop = FALSE)