1

我用这个例子:

df <- data.frame(start = c("2016-09-30 00:00:00", "2016-09-30 00:00:00", "2016-09-30 00:00:00"),  end = c("2017-03-12 00:00:00", "2017-06-30 00:00:00", "2017-12-01 00:00:00"))
library(dplyr)
library(lubridate)
df <- df %>% 
    mutate(across(everything(), ymd_hms),
           diff = as.numeric(difftime(end, start, units = 'days')))

但是我收到此错误:

Error in across(everything(), ymd_hms) : could not find function "across"

我该如何解决?

4

2 回答 2

3

添加dplyr::到变异

df <- data.frame(start = c("2016-09-30 00:00:00", "2016-09-30 00:00:00", "2016-09-30 00:00:00"),  end = c("2017-03-12 00:00:00", "2017-06-30 00:00:00", "2017-12-01 00:00:00"))
library(dplyr)
library(lubridate)
df <- df %>% 
  dplyr::mutate(across(everything(), ymd_hms),
         diff = as.numeric(difftime(end, start, units = 'days')))
于 2021-06-05T18:03:48.977 回答
1

您可以使用以下解决方案作为安全的替代方案:

library(lubridate)

DF %>%
  mutate(across(everything(), ~ ymd_hms(.x)), 
         diff = interval(start, end) / days(1))

       start        end diff
1 2016-09-30 2017-03-12  163
2 2016-09-30 2017-06-30  273
3 2016-09-30 2017-12-01  427
于 2021-06-05T18:06:10.893 回答