R学习笔记
学习书籍:《机器学习与R语言实战》 Yu-Wei Chiu
1.getwd():获得当前工作路径。
2.setwd(dir="path"):设置工作路径。setwd(dir="/Users/xxx/Documents/R/Learn/")
3.data():返回dataset包中的数据集。
4.data("iris"):将dataset中的iris数据集加载。
5.save(iris,file="路径"):将工作区的数据写入磁盘。
6.load("文件名"):将文件数据集加入工作区。
7.write.table(iris,file="iris.txt",sep=" "):将数据导出到文本文件,分隔符为空格。
8.write.csv(数据集,file="file.csv"):以csv格式存储文件。
9.read.csv,read.table等。
10.安装包
install.packages("WriteXLS")
11.导入包
library("WriteXLS")
12.WriteXLS("iris",ExcelFileName="iris.xls")
13.选择多列数据
iris[,c("Sepal.Length","Sepal.Width")]
iris[1:5,1:2]
14.str(iris):显示数据的内部结构。
15.条件筛选
iris[iris$[属性]=="值",1:3]
16.返回索引
which(iris$[属性]=="value")
17.iris[which(iris$[属性]=="value"),2:3]
18.subset函数
subset(iris,select=c("Sepal.Length","Sepal.Width"))
and运算:&&
subset(iris,Petal.Length <= 1.4 && Petal.Width >= 0.2,select=Species)
19.合并数据
将2个具有相同行或者列的数据框合并为一个。
flower.type = data.frame(Species = "setosa", Flower="iris")
merge(flower.type,iris[1:3,],by="Species")
因为2个数据框都有Species,所以就以Species为共有单元进行合并。
20.排序
order(数据集$属性,decreasing=TRUE) 返回索引
如:
order(iris$Sepal.Length,decreasing = TRUE)
[1] 132 118 119 123 136 106 131 108 110 126 130 103 51 53 121 140
[17] 142 77 113 144 66 78 87 109 125 141 145 146 59 76 55 105
[33] 111 117 148 52 75 112 116 129 133 138 57 73 88 101 104 124
[49] 134 137 147 69 98 127 149 64 72 74 92 128 135 63 79 84
[65] 86 120 139 62 71 150 15 68 83 93 102 115 143 16 19 56
[81] 80 96 97 100 114 65 67 70 89 95 122 34 37 54 81 82
[97] 90 91 6 11 17 21 32 85 49 28 29 33 60 1 18 20
[113] 22 24 40 45 47 99 5 8 26 27 36 41 44 50 61 94
[129] 2 10 35 38 58 107 12 13 25 31 46 3 30 4 7 23
[145] 48 42 9 39 43 14
21.head函数:查看数据集的前几行数据。
统计函数
1.均值
mean(数据集$属性)
2.方差
var(数据集$属性)
3.最大/最小
max/min(数据集$属性)
4.中位数
median(数据集$属性)
5.范围
range(数据集$属性)
6.四分数
quantitle(数据集$属性)
7.sd ??
sd(数据集$属性)
sapply:对数据框的每个数值型属性进行汇总统计,na.rm=TRUE代表忽略缺失值。
sapply(iris[1:4],mean,na.rm=True)
8.summary函数
summary(iris) 返回数据集的统计值预览。
9.关联性分析
cor(iris[,1:3]) 对iris的第1个到第3个属性进行关联性分析。
例如:
> cor(iris[,1:4])
Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length 1.0000000 -0.1175698 0.8717538 0.8179411
Sepal.Width -0.1175698 1.0000000 -0.4284401 -0.3661259
Petal.Length 0.8717538 -0.4284401 1.0000000 0.9628654
Petal.Width 0.8179411 -0.3661259 0.9628654 1.0000000
10.用cov()函数进行属性对的协方差计算
> cov(iris[,1:4])
Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length 0.6856935 -0.0424340 1.2743154 0.5162707
Sepal.Width -0.0424340 0.1899794 -0.3296564 -0.1216394
Petal.Length 1.2743154 -0.3296564 3.1162779 1.2956094
Petal.Width 0.5162707 -0.1216394 1.2956094 0.5810063t.est?
查看函数帮助:?函数名
来源:https://www.cnblogs.com/ghost-cat/p/5910860.html