1 初识R

1.1 安装R

R由R Core Team维护,R最新版本发布在官方网站,在官网找到安装文件下载链接,并选择距离最近的镜像网站下载(通常速度会更快)。

1.2 R Gui

启动R语言,在R Gui窗口中有菜单栏工具栏R控制台
evernotecid://6B344BC0-88B6-4BC2-9CCA-1B2113776B68/appyinxiangcom/531972/ENResource/p7180

  • R控制台(R console)用于输入指令和查看R系统反馈。
  • 输入的指令被称为表达式
  • R解释器读入表达式,并返回结果和错误信息。
  • 标准R Gui仅通过菜单实现非常初级的功能,但可以通过开源IDE如Rstudio或R扩展包如rattle丰富图形用户界面。

1.3 更新R

2 工作空间

工作空间是当前的R工作环境,包含了用户自定义对象。
Workplace is your current R working environment and includes any user-defined objects.

  • 工作空间管理函数
  1. getwd()
  2. # Find the current working directory (where inputs are found and outputs are sent)
  3. setwd("mydirectory")
  4. # Change the current working directory.
  5. ls() # List all variables in the environment.
  6. list.files() # list all the files in your working directory
  7. rm(x) # Remove x from the environment.
  8. rm(list = ls()) #Remove all variables from the environment.
  9. options() #
  10. q() # Quit R
  • 示例
  1. old.dir <- getwd()
  2. dir.create("testdir")
  3. setwd("testdir")
  4. file.create("mytest.R")
  5. file.exists("mytest.R")
  6. file.info("mytest.R")
  7. file.info("mytest.R")$mode
  8. file.rename("mytest.R","mytest2.R")
  9. file.copy("mytest2.R","mytest3.R")
  10. file.path("mytest3.R")
  11. file.path(folder1","folder2") # "folder1/folder2"
  12. dir.create(file.path('testdir2', 'testdir3'), recursive = TRUE)
  13. setwd(old.dir)

3 R语法

3 帮助文件

  1. # 帮助文件首页
  2. help.start()
  3. # Find help for a package
  4. help('PackageName')
  5. # Get help of a particular function,以下两式等价
  6. help('FunctionName')
  7. ?'FunctionName'
  8. # Search the help files for a word or phrase,以下两式等价
  9. help.search(‘weighted mean’)
  10. ??‘weighted mean

4 符号

Technically R is an expression language with a very simple syntax. It is case sensitive as are most UNIX based packages, so A and a are different symbols and would refer to different variables.

4.1 命令提示符

  1. # 在提示符prompt之后输入命令
  2. >

4.2 命令分隔符

  1. # Commands are separated either by a semi-colon (‘;’), or by a newline.
  2. x <- 2; y <- 3

4.2 赋值符

  1. # assignment operator
  2. # 左赋值,二元操作符(常用),Alt + "-"
  3. <-
  4. # 右赋值,二元操作符(不常用)
  5. ->
  6. # R语句由函数和赋值组成
  7. x <- 5 + 7
  8. y <- x - 3
  9. 7 -> z
  10. #
  11. <<-
  12. # 一般不使用"="赋值,而用来传参

4.3 传参符

  1. # '='只是将8传给了log函数的参数x,并没有在内存中创建x对象,打印x会报错
  2. log(x = 8, base = 2)
  3. # 表示在内存中创建x对象并赋值8,然后将x传递给log函数的第一个参数x,这时打印x就会输出x的值为8
  4. log(x <- 8, base = 2)

4.4 注释符

  1. # 这是注释,不会在程序中运行

4.5 帮助符

  1. # 函数帮助
  2. ?
  3. ??
  4. ?ggplot2

4.6 转义符

  1. \
  2. a <- "Hello, world"
  3. b <- 'Hello, world'
  4. # 以上两句完全等价
  5. a <- "You should use \"her\" in this 'passage'."
  6. b <- 'You should use "her" in this \'passage\'.'
  7. # 转义符来表明「特定的引号不是字符串定义结束,而是一个双引号字符」

4.6 链式符

  1. # chaning operator(margin)
  2. %<%

4.6 自动补全机制

  1. # auto-completion:tab键

4.7 命令回收机制

  1. # cycle through previous commands:向上箭头↑,向下箭头↓

4.8 数学运算

运算符是包含一个或者两个参数的无括号的函数。

  1. + # 加号,一元操作符或者二元操作符
  2. - # 减号,一元操作符或者二元操作符
  3. * # 乘法,二元操作符
  4. / # 除法,二元操作符
  5. ^(**) # 幂运算符,二元操作符
  6. x%%y # 求余,二元操作符
  7. x%/%y # 整除,二元操作符
  8. %*% # 矩阵相乘,二元操作符
  9. %o% # 外积,二元操作符
  10. %x% # Kronecker乘积,二元操作符
  11. # 注:矩阵有点积、内积、外积、元素积之分。

算数运算符 加(正):+ 减(负):- 乘: 除:/ 求幂:^(**) 求余:%% 整除:%/% 矩阵相乘:%% 外积:%o% 元素积:xor(x, y) Kronecker乘积:%x% 匹配:%in%(Ctrl + Shift + I) 逻辑运算符 大于:> 大于等于:>= 小于:< 小于等于:<= 等于:== 不等于:!= 或:|(||,只采用第一个元素) 且:&(&&,只采用第一个元素) 非:! 其他运算符

  • pipe:%>%(Ctrl + Shift + M)
  • 公式:~
  • 序列:’:’
  • 指定包公式:’::’
  • 列表子集:$
  • 索引:[ ]([[ ]])
  • 函数调用和分组表达式:({ })

4.9 逻辑判断

  1. < # 小于,二元操作符
  2. <= # 小于等于,二元操作符
  3. > # 大于,二元操作符
  4. >= # 大于等于,二元操作符
  5. == # 等于,二元操作符
  6. != # 不等于,二元操作符
  7. x|y # 或操作,二元操作符,向量模式
  8. x||y # 或操作,二元操作符,不是向量模式
  9. x&y # 与操作,二元操作符,向量模式
  10. x&&y # 与操作,二元操作符,不是向量模式
  11. ! # 一元否操作符

4.10 其他

  1. : # 序列colon,二元操作符
  2. :: # dplyr::select, Use a particular function from a package
  3. %in% # 匹配操作,二元操作符(在模型公式中,表示嵌套)
  4. ~ # 用于模型公式,一元操作符或者二元操作符
  5. %X% # 特殊二元操作符,X可以被任意合法的名字替换
  6. @ #
  7. $ # 子集subset
  8. '' #
  9. " " #
  10. () #
  11. [] # 子集subset
  12. [[]]
  13. {} #

5 R表达式

R基本命令由表达式和赋值组成。表达式输出结果而不存储,赋值存储结果而不输出。
Elementary commands consist of either expressions or assignments. If an expression is given as a command, it is evaluated, printed (unless specifically made invisible), and the value is lost. An assignment also evaluates an expression and passes the value to a variable but the result is not automatically printed.

  1. # 表达式,输出结果而不存储
  2. 5 + 7
  3. # 赋值,赋值存储结果而不输出
  4. x <- 2
  5. ## 在赋值外嵌套括号,既输出结果且存储结果
  6. (x <- 2)