关于包 包是一系列R函数和数据集的集合,库(library) 是电脑上的文件夹,而包就存储在文件夹的文件中 装了Rstdio 之后,默认的lattice 包已经被默认安装了
加载包 可以用library 函数
> library(lattice) > #使用lattice中的函数 > dotplot( variety ~ yield | site, data = barley, group = year) >
注意 包的名称被传递给Library的时候并不需要被括号括起来
用搜索路径来查看所有已加载的包
> search() [1] ".GlobalEnv" "package:lattice" "tools:rstudio" [4] "package:stats" "package:graphics" "package:grDevices" [7] "package:utils" "package:datasets" "package:methods" [10] "Autoloads" "package:base"
> View(installed.packages())
R出厂的包 在CRAN包库中,要访问其他存储库
> setRepositories()
在RGUI上 可以更加方便的在程序包部分来下载包
下载 github上的包
> install.packages("devtools")
> library(devtools)
> install_github("knitr","yihui")日期和时间的分析对于时间序列的分析尤为重要
R中标准的日期时间类为POSIXct ,用于存储和计算时间和POSIXlt用于提取日期中的某个部分,实际上是电脑内部的表达时间的格式,与一般的字符串表达有区别
Sys.time返回POSIXct的形式
> now_ct <- Sys.time() > now_ct [1] "2015-10-29 21:36:41 CST" > class(now_ct) [1] "POSIXct" "POSIXt"还有一种存储方式是 Date类
> date <- as.Date(now_ct) > date [1] "2015-10-29"
> moon <- c("20:17:40 20/07/1969") > moon [1] "20:17:40 20/07/1969" > moon_landing <- strptime(moon,"%H:%M:%S %d/%M/%Y",tz = "UTC") > moon_landing [1] "1969-10-20 20:07:40 UTC"要注意格式的变化
格式化字符串就是将电脑中时间表达的形式转化成字符串
> strftime(moon_landing,"%H:%M:%S %d/%M/%Y",tz = "UTC") [1] "20:07:40 20/07/1969"
查看操作系统的时区
> Sys.getlocale("LC_TIME") [1] "Chinese (Simplified)_China.936"
> now_ct [1] "2015-10-29 21:36:41 CST"
> now_ct + 86400 [1] "2015-10-30 21:36:41 CST"
可以使用difftime 函数 units 以秒或星期为单位
> difftime(as.Date(moon),as.Date(now_ct),units = "hours")可以使用lubridate包函数来解析函数
在时间程序包中,可以用ymd函数来指定特定的时间格式 如ydm,ymd,ymd_hms等 默认返回的都是POSIXct的日期,stamp函数还可以用来格式化日期
> now_ct <- c('1995-07-07','1978-08-08') > now_ct [1] "1995-07-07" "1978-08-08" > ymd(now_ct) [1] "1995-07-07 UTC" "1978-08-08 UTC"
[1] "2015-10-30" > duration_ <- dyears(1:10) > today()+duration_ [1] "2016-10-29" "2017-10-29" "2018-10-29" "2019-10-29" "2020-10-28" "2021-10-28" [7] "2022-10-28" "2023-10-28" "2024-10-27" "2025-10-27"
> y <- years(1:10) > today()+y [1] "2016-10-30" "2017-10-30" "2018-10-30" "2019-10-30" "2020-10-30" "2021-10-30" [7] "2022-10-30" "2023-10-30" "2024-10-30" "2025-10-30"
> a_year <- dyears(1) > as.period(a_year) estimate only: convert durations to intervals for accuracy [1] "1y 0m 0d 0H 0M 0S"
> head(olson_time_zones()) [1] "Africa/Abidjan" "Africa/Accra" "Africa/Addis_Ababa" "Africa/Algiers" [5] "Africa/Asmara" "Africa/Bamako"
> floor_date(today(),"year") [1] "2015-01-01" > ceiling_date(today(),"year") [1] "2016-01-01"