2014/11/20

[R] 第5篇 資料操作 (中)

R 的資料操作

日期及時間是資料表中常出現的欄位,在 R 中使用 date,主要為 as.Date(),用 Sys.Date() 可以拿到現在的日期,Sys.time() 能拿到含有時間的詳細資訊。如果要將 date 輸出成特定的格式,可以用 format 來幫忙,而 format 的表示式要怎麼寫,詳細請參考 R 的文件,要將 date 轉成 character,可以用 as.character()。反之,如果要將 character 轉成 date,用 as.Date() 或是 strptime。一般來說,因為時區的不同,所以要有一個通用的表示方式,那就是國際標準時間 ISO-8601。
> Sys.Date()
[1] "2014-11-20"
> Sys.time()
[1] "2014-11-20 21:58:24 CST"
> date()
[1] "Thu Nov 20 21:57:24 2014"

## print date
> format(Sys.Date(), format = "%m/%d/%Y")
[1] "11/20/2014"
> format(Sys.time(), format = "%m/%d/%Y %H:%M:%S")
[1] "11/20/2014 22:07:41"
> format(Sys.time(), format = "%x %X")
[1] "20/11/2014 22:08:57"

## date -> character
> as.character(Sys.time())
[1] "2014-11-20 22:20:53"

## character -> date
> sDates <- c("2014-11-20", "2014-11-21")
> dates <- as.Date(sDates, format = "%Y-%m-%d")
> dates
[1] "2014-11-20" "2014-11-21"
> class(dates)
[1] "Date"

## date default value is today, timezone default is user locale
> times <- c("00:03:04", "06:03:04", "12:05:06", "18:05:06")
> strptime(times, "%H:%M:%S")
[1] "2014-11-20 00:03:04 CST" "2014-11-20 06:03:04 CST"
[3] "2014-11-20 12:05:06 CST" "2014-11-20 18:05:06 CST"
format 表示式說明
http://www.stat.berkeley.edu/~s133/dates.html
https://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html

如果要作型態轉換時,可以用 as.numeric()as.character(),而要判斷某變數是否屬於某型態時,就用 is.na()is.vector() 等等。
> x <- c("1", "2")
> is.character(x)
[1] TRUE
> is.vector(x)
[1] TRUE
> x <- as.numeric(x)
> is.numeric(x)
[1] TRUE
> is.character(x)
[1] FALSE
> is.vector(x)
[1] TRUE
cbindrbind,是用來合併 vector,合成的方式分別為 column 為主及 row 為主。
> x <- 3:5
> y <- 7:9
> rbind(x, y)
  [,1] [,2] [,3]
x    3    4    5
y    7    8    9
> cbind(x, y)
     x y
[1,] 3 7
[2,] 4 8
[3,] 5 9

沒有留言:

張貼留言