简体   繁体   English

如何计算 R 中的天数

[英]How to count number of days in R

I have this type of dataframe我有这种类型的 dataframe

DF
ID   DATE_FROM     DATE_TO
1.   01.01.2020    05.01.2020
2.   05.01.2020    11.01.2020
3.   31.01.2020    05.02.2020

We use this format of date in CZE and it means我们在 CZE 中使用这种日期格式,这意味着

DD.MM.YYYY DD.MM.YYYY

I would like to get this:我想得到这个:

DF
ID   DATE_FROM     DATE_TO       NUM.OF.DAY
1.   01.01.2020    05.01.2020    4
2.   05.01.2020    11.01.2020    6
3.   31.01.2020    05.02.2020    5

So I would need to do basic subtraction所以我需要做基本的减法

I tried this:我试过这个:

 DF %>%
   mutate(DATE_FROM = as.Date(DATE_FROM)) %>%
   mutate(DATE_TO  = as.Date(DATE_TO)) %>%
   mutate(NUM.OF.DAY = DATE_TO - DATE_FROM)

but with no result但没有结果

You need to parse the dates and specify the format in which they are written in order to perform operations between them.您需要解析日期并指定它们的写入格式,以便在它们之间执行操作。

(As a side note, you can use only one mutate statement instead of three) (作为旁注,您只能使用一个mutate语句而不是三个)

DF %>% 
  mutate(DATE_FROM = as.Date(DATE_FROM, format = "%d.%m.%Y"),
         DATE_TO = as.Date(DATE_TO, format = "%d.%m.%Y"),
         NUM_OF_DAY = as.numeric(DATE_TO - DATE_FROM))

Output Output

#   ID  DATE_FROM    DATE_TO NUM_OF_DAY
# 1  1 2020-01-01 2020-01-05          4
# 2  2 2020-01-05 2020-01-11          6
# 3  3 2020-01-31 2020-02-05          5

Data:数据:

df <- data.frame(
  ID = 1,
  DATE_FROM = as.Date("01.02.2020", "%d.%m.%Y"),
  DATE_TO = as.Date("12.03.2020", "%d.%m.%Y")
)

Solution in base R : base R中的解决方案:

df$NUM.OF.DAY <- as.numeric(df$DATE_TO - df$DATE_FROM)

Result:结果:

df
  ID  DATE_FROM    DATE_TO NUM.OF.DAY
1  1 2020-02-01 2020-03-12         40

Another option:另外的选择:

difftime(as.POSIXct('12.03.2020', format = "%d.%m.%Y"), 
         as.POSIXct('01.02.2020', format = "%d.%m.%Y")
         )

#Time difference of 40 days

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM