R語言入門教程

安装包

install.packages('')
library()
update.packages()

向量

v=c(1,2,3,4)
v[c(2,3,4)]
v[v<3]
which(v==3)
v=v[-2]  v=v[-2:-4]

生成数字:

生成三个随机数a=runif(3,min=0,max=100) 取整floor(a) ceiling(a) round(a,4) 生成正态分布的数rnorm 设定随机数set.seed()

导入数据

read.csv()

生成矩阵

x=matrix(数字, nrow= , ncol= , byrow=TRUE)

set.seed(123)
A = matrix(sample(100,15), nrow=5, ncol=3)

提取矩阵里的因素: x[第几行,第几列] 给每行每列命名:

rnames=c()
cnames=c()
x=matrix()
rownames(x)=
colnames(x)=

多维矩阵(Array):

dim1=c("", "")
dim2=c("", "")
......
z=array(数字, c(第几维有几个变量 , ), dimnames= list(dim1, dim2, dim3, ...)

从多维矩阵里面取出数字: z=[1,2,3, ]

Data Frame(图表)

x1=c()
x2=c()
......
data=data.frame(x1, x2, , , )

从中取出行和列 data[第几行, 第几列]

List(许多图表的集合)

mylist=list( , , )

画图

建立一个存放图像的2*2表格

par(mfrow=c())
title(main="")

bar chart

barplot(counts,
main="Stacked Bar Plot",
xlab="Treatment", ylab="Frequency",
col=c("red", "yellow","green"),
legend=rownames(counts))

pie chart

library(plotrix)
par(mfrow=c(2,2))
slices <- c(10, 12,4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pie(slices, labels = lbls,main="Simple Pie Chart",edges=300,radius=1)
pct <- round(slices/sum(slices)*100)
lbls2 <- paste(lbls, " ", pct, "%", sep="")
pie(slices, labels=lbls2, col=rainbow(length(lbls2)),
main="Pie Chart with Percentages",edges=300,radius=1)
pie3D(slices, labels=lbls,explode=0.1,
main="3D Pie Chart ",edges=300,radius=1)

fan.plot(slices, labels = lbls, main="Fan Plot")

dot plot

dotchart(mtcars$mpg,
labels=row.names(mtcars),cex=0.7,
main="Gas Mileage for Car Models",
xlab="Miles Per Gallon")

循环结构

For循环

for(i in 1:10){
  print(i)
}

While循环

i=1
while(i<=10){
  print(i)
  i=i+1
}

判断结构

if statement
i=1
if (i==1){
  print("")
}else{
  print("")
}

switch(A,B)
feelings= c ("","")
for(i in feelings){
  print(
    switch(i,

设定函数

myfunction = function(x,a,b,c){
  return(a*sin(x)^2 - b*x +c)
}               

t Test

t.test(x, y, alt = "two.sided",paired=TRUE)

打开一个csv文件

mydata<-read.csv('C:/Users/Think/Desktop/UKNGDP - 副本.csv')

画图

bar plot

plot(cars$dist~cars$speed)#data.frame的名字$变量名

画一个函数的图:

curve(函数, from= , to= )

results matching ""

    No results matching ""