2017-06-22 61 views
0

我試圖計算內dplyr::mutate個月的兩個日期之間的號碼,但碰上錯誤使用dplyr內序列變異的功能

Error in mutate_impl(.data, dots) : 'from' must be of length 1 

有一些關於seq這是不符合mutate

library(dplyr) 
dset <- data.frame(f = as.Date(c("2016-03-04","2016-12-13","2017-03-01")) , 
        o = as.Date(c("2016-03-04","2016-12-13","2017-06-02"))) 
dset %>% mutate(y = length(seq(from=f, to=o, by='month')) - 1) 
+0

您傳遞給'seq'函數的是一個數組,它只能接受單個值。 –

回答

2

要解決它,您可以使用sapplymapply。否則,您可以使用lubridate中的函數從日期中提取月份,然後計算差異。

library(dplyr) 
library(lubridate) 
# Sapply 
dset %>% 
    mutate(y=sapply(1:length(f), function(i) length(seq(f[i], o[i], by="month")) - 1)) 

# Mapply 
dset %>% 
    mutate(y=mapply(function(x, y) length(seq(x, y, by="month")) - 1, f, o)) 

# function in lubridate 
dset %>% mutate(y=month(o) - month(f)) 
+1

如果您使用'lapply' /'sapply'來迭代索引,這是您應該使用'Map' /'mapply'的標誌。 – alistaire

+1

已添加回答。謝謝! – JasonWang

0

您可能還需要使用dplyr本:

dset <- data.frame(f = as.Date(c("2016-03-04","2016-12-13","2017-03-01")) , 
        o = as.Date(c("2016-03-04","2016-12-13","2017-06-02"))) 

dset %>% mutate(y = as.numeric(difftime(f,o, units = "weeks"))/4) 
+0

你是對的。 Mea culpa。 – akash87

0

您需要組,迭代,或調整,使得每個fromto參數是長度爲1(seq(1, 5)是細; seq(1:2, 5:6)不是),這意味着rowwise或也許group_by_all

library(dplyr) 

dset <- data.frame(f = as.Date(c("2016-03-04","2016-12-13","2017-03-01")) , 
        o = as.Date(c("2016-03-04","2016-12-13","2017-06-02"))) 

dset %>% 
    rowwise() %>% 
    mutate(y = length(seq(f, o, by = 'month')) - 1) 

#> Source: local data frame [3 x 3] 
#> Groups: <by row> 
#> 
#> # A tibble: 3 x 3 
#>   f   o  y 
#>  <date>  <date> <int> 
#> 1 2016-03-04 2016-03-04  0 
#> 2 2016-12-13 2016-12-13  0 
#> 3 2017-03-01 2017-06-02  3 
0

「alistaire」做了一些錯字錯誤,所以答案錯了

dset %>% 
    rowwise() %>% 
    mutate(y = length(seq(f, o, by = 'month')) - 1) 

Source: local data frame [3 x 3] 
Groups: <by row> 

# A tibble: 3 x 3 
      f   o  y 
     <date>  <date> <dbl> 
1 2016-03-04 2016-03-04  0 
2 2016-12-13 2016-12-13  0 
3 2017-03-01 2017-06-02  3