Help us understand the problem. What is going on with this article?

Rの時刻変換と日の差分【lubridate, Time Intervals, Differences day】

時刻変換する方法は色々ある。

Rの中で時刻データとして変換してやると、

https://stat.ethz.ch/R-manual/R-devel/library/base/html/difftime.html

ここに乗っているようなことができる。
自分でちょこちょこ調べる周辺まとめておく。

日の差分を求めることが今回の目的

as.Dateで

start <- as.Date("20200101", format="%Y%m%d")
end <- as.Date("20200201", format="%Y%m%d")

end - start
Time difference of 31 days

difftime関数も同じことやっている

difftime(end, start)

as.POSIXでも

start <- as.POSIXct("20200101", format="%Y%m%d")
end <- as.POSIXct("20200201", format="%Y%m%d")
difftime(end, start)
Time difference of 31 days

lubridateほんと最高

library(lubridate)

start <- ymd("20200101")
end <- ymd("20200201")

difftime(end, start)
Time difference of 31 days

as.numericで数字に直す

as.numeric(difftime(end, start))
[1] 31

おまけ

気持ちを察してくれるlubridateさん

ymd("20200501")
[1] "2020-05-01"
ydm("20200501")
[1] "2020-01-05"
mdy("08202000")
[1] "2000-08-20"
ymd_hms("20200201003059", tz="Japan")
[1] "2020-02-01 00:30:59 JST" 
ymd_h("2020020120", tz="Japan")
[1] "2020-02-01 20:00:00 JST"

曜日も出してくれる優しいヤツ

wday(ymd("20200501"))
[1] 6
wday(ymd("20200502"))
[1] 7
wday(ymd("20200503"))
[1] 1

ちなみに
1が月曜日
7が日曜日

lubridateさんホント最高
他にも差分をとる方法は色々あるので以下参照

https://lubridate.tidyverse.org/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした