簡體   English   中英

從R中的日期列計算並添加列length_of_time

[英]Calculate & add column length_of_time from date column in R

我正在嘗試創建一個新的計算字段length_of_time 我有一個帶有日期的final_date列:

2/10/2016  
4/4/2016  
5/8/2016  
10/1/2016

並且我正在嘗試計算一個新字段,該字段顯示2016年10月23日至final_date之間的時間長度。

我嘗試使用dplyr:

mutate(df, length_of_time = 10/23/2016 - final_date) 

並收到一個錯誤:

“ eval(substitute(expr),envir,enclos)中的錯誤:只能從“ POSIXt”對象中減去”

所以我嘗試使用:

df <- as.POSIXlt(df$final_date)

再次運行我的原始代碼,只收到以下錯誤:

Error in UseMethod("mutate_") : 
  no applicable method for 'mutate_' applied to an object of class "c('POSIXlt', 'POSIXt')"

日期格式有些混亂。 (請參閱代碼注釋以獲取解釋)

library(dplyr)

df <- data.frame(final_date = c("2/10/2016","4/4/2016"))

## you need to specify the format of your date columns as it is ambiguous
## I've guessed you're using day/month/year
df$final_date <- as.POSIXct(df$final_date, format = "%d/%m/%Y")

## and you need to subtract the `final_date` (which is POSIXct) 
## from another POSIXct object
mutate(df, length_of_time = as.POSIXct("2016-10-23") - final_date)

final_date length_of_time
1 2016-10-02  20.95833 days
2 2016-04-04 201.95833 days

進一步閱讀

為了幫助理解POSIXctPOSIXlt之間的區別,日期格式,日期計算等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM