Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在数据帧中添加一个新列,该列的开始时间戳和结束时间戳之间的天数为_R - Fatal编程技术网

R 在数据帧中添加一个新列,该列的开始时间戳和结束时间戳之间的天数为

R 在数据帧中添加一个新列,该列的开始时间戳和结束时间戳之间的天数为,r,R,有一个带有开始和结束时间戳的数据帧,如下所示: 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:0

有一个带有开始和结束时间戳的数据帧,如下所示:

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"))

df我们可以使用
difftime

library(dplyr)
library(lubridate)
df <- df %>% 
   mutate(across(everything(), ymd_hms),
         diff = as.numeric(difftime(end, start, units = 'days')))

我们可以使用
%--%%

输出:

                start                 end difference
1 2016-09-30 00:00:00 2017-03-12 00:00:00        163
2 2016-09-30 00:00:00 2017-06-30 00:00:00        273
3 2016-09-30 00:00:00 2017-12-01 00:00:00        427
library(lubridate)
df %>% 
  mutate(span = start %--% end) %>% 
  mutate(difference = as.numeric(span, unit = 'day'), .keep ="unused")
                start                 end difference
1 2016-09-30 00:00:00 2017-03-12 00:00:00        163
2 2016-09-30 00:00:00 2017-06-30 00:00:00        273
3 2016-09-30 00:00:00 2017-12-01 00:00:00        427