- 20151208 [Coursera] R Programming (10)
- 整理自 R Programming (Week 2)
- [ Week 2 課程內容 ]
- [ 筆記內容 ]
- (一)Coding Standards
- [重點整理] 撰寫程式的基本規範
- 1. 使用"文本格式"(text files)來儲存資料。
- 2. 經常使用"縮排"(Indent),同時要記得限制每一行程式的寬度。
- 3. 將一系列複雜的功能製作成函數分類,同時限制個別函數的長度,可以讓程式簡單化。
- (二)Dates and Times
- [ 重點整理 ]
- 1. Dates and Times in R
- 2. Dates in R
- 3. Times in R
- 4. Operations on Dates and Times
- 5. Summary
Visible to members of this folder
整理自 R Programming (Week 2)
Control Structures - Introduction[0:54](已完成)Control Structures - If-else[1:58](已完成)Control Structures - For loops[4:25](已完成)Control Structures - While loops[3:22](已完成)Control Structures - Repeat, Next, Break[4:57](已完成)Your First R Function[10:29](僅觀看)Functions(part1)[9:17](已完成)Functions(part2)[7:13](已完成)Scoping Rules - Symbol Binding[10:32](已完成)Scoping Rules - R Scoping Rules[8:34](已完成)Scoping Rules - Optimization Example(OPTIONAL)[9:21](已完成)(一)Coding Standards
(二)Dates and Times
# Dates in R
> x <- as.Date("1970-01-01")
> x
[1] "1970-01-01"
>
> unclass(x) # 消除"x"的類別
[1] 0 # 因為"1970-01-01"與 R 內部預設的基準日期"1970-01-01"相差"0"天,所以得到數字"0"
>
> unclass(as.Date("1970-01-02"))
[1] 1 # 因為"1970-01-02"與 R 內部預設的基準日期"1970-01-01"相差"1"天,所以得到數字"1"
>
# Times in R (使用"as.POSIXlt()"轉換類型)
> x <- Sys.time() # 顯示系統目前的時間
> x
[1] "2015-12-08 15:55:01 CST"
>
> p <- as.POSIXlt(x) # 使用"as.POSIXlt()"轉換類型,(提示:"POSIXlt"類別的儲存型態為"列表")
> names(unclass(p))
[1] "sec" "min" "hour" "mday"
[5] "mon" "year" "wday" "yday"
[9] "isdst" "zone" "gmtoff"
> p$sec
[1] 1.995
>
# Times in R ("POSIXct"型態)
> x <- Sys.time() # 顯示系統目前的時間
> x # "x"已經以"POSIXct"型態儲存
[1] "2015-12-08 16:07:49 CST"
>
> unclass(x)
[1] 1449562069 # 取得"1970-01-01"至今的秒數
> x$sec
Error in x$sec : $ operator is invalid for atomic vectors
>
> p <- as.POSIXlt(x) # 使用"as.POSIXlt()"轉換類型,(提示:"POSIXlt"類別的儲存型態為"列表")
> p$sec
[1] 49.431
>
# strptime()
> x <- strptime(c("2006-01-08 10:07:52", "2006-08-07 19:33:02"), "%Y-%m-%d %H:%M:%S", tz = "EST5EDT")
> x
[1] "2006-01-08 10:07:52 EST" "2006-08-07 19:33:02 EDT"
>
> class(x)
[1] "POSIXlt" "POSIXt"
>
# 對日期進行減法,比較兩個日期之間的差異(1)
> x <- as.Date("2012-01-01") # "Date" 類別
> y <- strptime("2011-01-09 11:34:21", "%Y-%m-%d %H:%M:%S", tz = "EST5EDT") # "POSIXlt" 類別
> x-y # 不同類別之間無法進行運算
Error in x - y : non-numeric argument to binary operator
In addition: Warning message:
Incompatible methods ("-.Date", "-.POSIXt") for "-"
> x <- as.POSIXlt(x) # 將 "Date" 類別轉換為 "POSIXlt" 類別
> x-y
Time difference of 356.3095 days
>
# 對日期進行減法,比較兩個日期之間的差異(2)
# 適用於"平、閏年"、"閏秒"、"時區"之間的差異計算
> x <- as.Date("2012-03-01") # 註:西元2012年是"閏年",所以有"2月29日"
> y <- as.Date("2012-02-28")
> x-y
Time difference of 2 days # 因為西元2012年是"閏年",所以"3月1日"跟"2月28日"差2天
>
> x <- as.POSIXct("2015-12-08 21:00:00") # 取得電腦目前所在的時間,在這裡是"台北(UTC)"時區
> y <- as.POSIXct("2015-12-08 18:00:00", tz = "GMT") # 取得"格林尼治(GMT)"時區對應時間
> y-x
Time difference of 5 hours
>