dplyr动态生成要变异的列

时间:2017-09-04 00:16:44

标签: r dplyr

我有一个数据框,其中包含一个日期列,一个金额的另一列以及包含年份的各个列。我想将amount列中的值放入与date列中的year对应的year列。例如,

ID    Date         Amount        2010    2011    2012
01    2010/05/05   200           200
02    2011/05/05   300                   300
03    2012/05/05   400                           400

有没有办法可以根据日期列的值动态选择要变异的列?

2 个答案:

答案 0 :(得分:4)

使用lubridate year将日期转换为年份后,您可以使用spread包中的tidyr将数据传播出去:< / p>

library(dplyr)
library(tidyr)
df = read.table(text = "ID    Date         Amount
            01    2010/05/05   200        
            02    2011/05/05   300     
            03    2012/05/05   400 ", header= TRUE)

df %>% 
    mutate(y = lubridate::year(Date)) %>% 
    spread(key = y, value = Amount)

缺少的数据点将是NA&#39。如果您喜欢样本中的空白字符串,请尝试:

... %>%
    spread(key = y, value = Amount, fill = "")

请注意,生成的数据框不再具有Amount列,但您可以通过合并到原始数据来恢复它。

答案 1 :(得分:1)

为了完整起见,还有一个&#34; one-liner&#34;使用data.table

library(data.table)
dcast(DF, ID + Date + Amount ~ year(Date), fill = "")

请注意,year列是即时计算的。因此,在重新整形之前无需创建辅助y变量。

  ID       Date Amount 2010 2011 2012
1 01 2010-05-05    200  200          
2 02 2011-05-05    300       300     
3 03 2012-05-05    400            400

数据

DF <- structure(list(ID = c("01", "02", "03"), Date = structure(c(14734, 
15099, 15465), class = "Date"), Amount = c(200L, 300L, 400L)), .Names = c("ID", 
"Date", "Amount"), row.names = c(NA, -3L), class = "data.frame")