R语言学习笔记
前言
本文主要记录了R语言学习过程中一些较为常用的函数,算是总结一下最近一段时间学习到的知识点,也可以给大家提供相应的参考,后续也将持续更新(本人新手刚刚接触R语言,如有错误还望各位大佬多多指教~)。
正文
1.查看安装包版本
// Check the packages version
packinfo <- installed.packages()
packinfo[,c("Package", "Version")]
2.查看R版本
// Check the R version
version
3.查看程序包安装路径
// Check the path of installed packages
.libPaths()
4.安装R包/指定版本的R包
// package installation
install.packages("...") #引号不可省略
install_version("...",version="...",repos="http://cran.us.r-project.org") #引号不可省略
5.获取当前工作路径
// get current work directory
getwd()
6.清空变量区某变量/所有变量
// Clear the variable
rm(name) # name为变量名
rm(list = ls())
7.清空Console控制台
// Clear the console
Ctrl + L # 键盘输入
cat("\014")
8.部分输出函数
// print function
print (x ,quote=FALSE) # 输出单个变量
cat(x,'a','b','\n') # 输出多个变量,'\n'为换行
9.调用.R文件
// call function in other .R file
source('fun.R') # fun.R文件在默认路径
source('F:\Code_Summary\R_code\fun.R') # fun.R文件在其他路径
10.plot绘图函数
// example:plot
plot(x=c(1:10),y=c(1:10),main='test',col=c("red"),xlim = c(0, 15), xlab = 'x_test',axes = TRUE,cex.main = 1, font.main= 4, col.main= "blue")
plot函数常用参数配置
Parameter | Value |
---|---|
x | x 轴点的坐标 |
y | y 轴点的坐标 |
main | 图标题 |
col.main | 标题颜色 |
col | 绘图颜色 |
xlab / ylab | x轴 / y轴标题 |
xlim / ylim | x轴 / y轴范围 |
font.main | 标题字体 |
cex.main | 标题大小 |
11.par函数:调整绘图参数
// example:par
par(mfrow = c(1,1)) # 设置子图数量及排列(1行2列)
par(bg = "cyan") # 设置绘图背景颜色
par(mar = c(1, 1, 0.5, 0.5)) # 设定下、左、上、右间隔
12.图中加入文字
// example:par
text(x=c(1:10),y=c(1:10),labels=c(1:10),cex=0.9,col="red") # label代表文字内容
13.绘制水平线
// plot the horizontal line
abline(h=3,col="red")
实验效果
par(mfrow = c(1,1))
par(bg = "powderblue")
par(mar = c(5, 5, 5, 5))
plot(x=c(1:10),y=c(1:10),main='test image',col=c("red"),xlim = c(0, 15), xlab = 'x_label', ylab = 'y_label',
axes = TRUE,cex.main = 1, font.main= 12, col.main= "blue")
abline(h=3,col="red")
text(x=c(1:10),y=c(1:10)-0.3,labels=c(1:10),cex=0.9,col="red")
14.获取数据类型
# class & mode & typeof comparison
> a<-matrix(c(1:12),ncol=3)
> a
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> class(a) # 获取输入对象的数据类型
[1] "matrix" "array"
> mode(a) # 获取输入对象中元素的数据类型
[1] "numeric"
> typeof(a) # 获取元素的数据类型(较mode更详细一些)
[1] "integer"
若为嵌套结构,上述三种方法仅能获取输入对象的数据类型:
> b=list(a,a,a)
> class(b)
[1] "list"
> mode(b)
[1] "list"
> typeof(b)
[1] "list"
> b[1]
[[1]]
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
# 若要获取嵌套列表内元素的数据类型,需通过将列表元素单独作为输入
> class(b[[1]])
[1] "matrix" "array"
> mode(b[[1]])
[1] "numeric"
> typeof(b[[1]])
[1] "integer"
初来乍到,可能有很多不对的地方,如有笔误还请各位大佬多多指教~