如何通过管道功能设置整行的值

时间:2019-03-15 16:55:17

标签: r dplyr

我试图通过使用dplyr的管道函数将数据帧第一行的默认值设置为1。

使用日期函数动态组合数据中的值是其要求之一。如果有人可以帮助我了解如何为下面提到的代码中的所有第一行设置默认值,我将不胜感激。我已经创建了一个占位符,希望输入默认值。

df2 <- df %>% mutate(MonthDate = as.Date(df$StartMonth,"%m/%d/%Y")) %>%
  filter(MonthDate > as.Date("2005-09-30"))%>%
  # Place holder where I want to set first row of the column to default value of 1#
  mutate(SAABenchmark_VAMI = cumprod(exp(SAABenchmarkstdev)),
         SAABetaOnly_VAMI = cumprod(exp(SAABetaOnly_stdev)),
         HFbenchmark_VAMI = cumprod(exp(HFbenchmarkReturns)),
         ZAAMHF_VAMI = cumprod(exp(ZAAMHFReturns)))%>%
  mutate(SAABenchmark_logVAMI =log(SAABenchmark_VAMI),
         SAABetaOnly_logVAMI=log (SAABetaOnly_VAMI),
         Hfbenchmark_logVAMI=log(HFbenchmark_VAMI),
         ZAAMHF_logVAMI=log(ZAAMHF_VAMI))%>%
  select(MonthDate,SAABenchmark_VAMI:ZAAMHF_logVAMI)%>%
  melt(., id.vars = "MonthDate")

也请找到我的数据框:

structure(list(StartMonth = structure(c(2L, 9L, 11L, 13L, 15L, 
17L, 19L, 21L, 23L, 4L, 6L, 8L, 3L, 10L, 12L, 14L, 16L, 18L, 
20L, 22L, 24L, 5L, 7L, 1L), .Label = c("", "1/31/2017", "1/31/2018", 
"10/31/2017", "10/31/2018", "11/30/2017", "11/30/2018", "12/31/2017", 
"2/28/2017", "2/28/2018", "3/31/2017", "3/31/2018", "4/30/2017", 
"4/30/2018", "5/31/2017", "5/31/2018", "6/30/2017", "6/30/2018", 
"7/31/2017", "7/31/2018", "8/31/2017", "8/31/2018", "9/30/2017", 
"9/30/2018"), class = "factor"), SAABenchmarkstdev = c(47L, 48L, 
49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 
62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, NA), SAABetaOnly_stdev = c(26L, 
27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 
40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, NA), HFbenchmarkReturns = c(34L, 
35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 
48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, NA), ZAAMHFReturns = c(47L, 
48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 
61L, 62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, NA)), class = "data.frame", row.names = c(NA, 
-24L))

1 个答案:

答案 0 :(得分:1)

您可以使用mutate_at()做一些事情。

在这里,我删除了不想添加1的列作为vars()中的第一行。然后,在其余列中将第一行设置为1,我将1与值的矢量减去第一个值连接起来。

df %>% 
     mutate(MonthDate = as.Date(df$StartMonth,"%m/%d/%Y")) %>%
     filter(MonthDate > as.Date("2005-09-30")) %>%
     mutate_at(vars(-MonthDate, -StartMonth), list(~c(1, .[-1])))

   StartMonth SAABenchmarkstdev SAABetaOnly_stdev HFbenchmarkReturns ZAAMHFReturns  MonthDate
1   1/31/2017                 1                 1                  1             1 2017-01-31
2   2/28/2017                48                27                 35            48 2017-02-28
3   3/31/2017                49                28                 36            49 2017-03-31
...