gpt4 book ai didi

r - 在 dplyr mutate 中使用 seq 函数

转载 作者:行者123 更新时间:2023-12-03 09:08:48 25 4
gpt4 key购买 nike

我正在尝试计算 dplyr::mutate 中两个日期之间的月数,但遇到错误

 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 )

最佳答案

要解决此问题,您可以使用 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))

关于r - 在 dplyr mutate 中使用 seq 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44704612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com