7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

arの表紙の長澤まさみが本当に可愛い

Last updated at Posted at 2013-07-09

大体の言語でdatetimeの型変換面倒くさい

R
> s <- "2013-07-07 10:00:00 UTC"
> class(s)
# => [1] "character"
> as.Date(s)
# => [1] "2013-07-07"
> as.POSIXct(s)
# => [1] "2013-07-07 10:00:00 JST"
> as.POSIXlt(s)
# => [1] "2013-07-07 10:00:00"

timezoneの情報消えとるやんけ

R
> as.POSIXct(s, format = "%Y-%m-%d %H:%M:%S", tz = "UTC")
# => [1] "2013-07-07 10:00:00 UTC"

factorでもいける

R
> df <- read.delim("data")
> head(df$date, 1)
# => [1] 2009-06-20 02:41:45 UTC
> class(df$date, 1)
# => [1] "factor"
> as.POSIXct(df$date, tz = "UTC")
# 以下にエラー as.POSIXlt.character(as.character(x), ...) : 
# 文字列は標準的な曖昧さのない書式にはなっていません
# などと怒られるので渡すformatを指定して教えてあげる
> df$date <- as.POSIXct(df$date, format = "%Y-%m-%d %H:%M:%S", tz = "UTC")
> df$date
# => [1] "2009-06-20 02:41:45 UTC" "2009-08-04 07:35:48 UTC"
# ...
> class(df$date)
# => [1] "POSIXct" "POSIXt" 

だいたい型変換するとNAになるやつあるから殺す

R
df <- df[!is.na(df$date),]

これで時系列データの可視化も超簡単
しかし今回は月別に集計したいので文字列に戻す

datetimeにした意味とはなんだったのかとか言わないこと

R
> df$month <- strftime(df$date, format = "%Y/%m")
> ggplot2(df, aes(df$month, df$score)) + geom_boxplot() + stat_summary(fun.y = mean, geom = "line", aes(group = 1))

欲しかったボックスプロットに移動平均はこれでできた
POSIXctを丸め込むのに{lubridate}のfloor_date関数を使ってもよさそう
reference

ちなみにggplot 0.9.3だとエラーが出てgroupが効かない
0.9.3.1にしたらちゃんと移動平均描けた

R
> ggplot2(df, aes(df$month, df$score)) + geom_boxplot() + stat_summary(fun.y = mean, geom = "line", aes(group = 1))
# geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?

でもこれだとX軸がmonthに依存するから折角datetimeなのにもったいなくない?
でもそのままぶち込むとX軸が連続値だし怒られるので公式documentにあるgroupとround_anyを使って丸め込む

R
> library(plyr)
> ggplot(df, aes(df$date, df$normalized_phred_score)) + geom_boxplot(aes(group = round_any(df$date, 60*60*24*30*6, floor)))

これで描ける

四半期とかでまとめたい時はformatとかfloor_dateとか使えないのでどうにかならんもんかと思っていたわけです
packageあるやろと
ジュール・ベルヌもこのように偉大な言葉を残しているわけです
package誰か作っとるやろと

しかし探せどないわけです、round系の関数にいい具合のオプションを渡してあげたら10日とか3ヶ月とかでまるめてくれんものかと
xtsというpackageに便利な関数がいろいろあると教えてもらったのだけれど
うまくいかず

ところが

R
> quarters(df$date)
# => [1] "Q2" "Q3" "Q3" "Q3" "Q3" "Q3"
# ...

あった…

R
> df$qtr <- paste(format(df$date, "%Y"), quarters(df$date), sep = "/")

これでいいやんね

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?