數(shù)學(xué)函數(shù)
#round(x,digits=n)小數(shù)位數(shù),signif(x,digits=n)有效數(shù)字位數(shù),trunc()直接去除小數(shù)
#log(x,base=n)對x取以n為底的對數(shù)
#統(tǒng)計(jì)函數(shù)
#sd(x)標(biāo)準(zhǔn)差呆馁,range(x)求值域染苛,diff(x,lag=n)求滯后差分鹊漠,
#scale(x,center=TRUE,scale=TRUE)對數(shù)據(jù)對象x進(jìn)行中心化或者標(biāo)準(zhǔn)化
#進(jìn)行任意均值和方差的標(biāo)準(zhǔn)化
#對矩陣或者數(shù)據(jù)框
newdata <- scale(mydata)
newdata <- scale(mydata)*SD+M
#SD標(biāo)準(zhǔn)差主到,M均值
#對某一列進(jìn)行標(biāo)準(zhǔn)化
newdata <- transform(mydata,myvar=scale(myvar)*10+50)
x <- c(1,2,3,4,5,6,7,8)
mean(x)
sd(x)
n <- length(x)
meanx <- sum(x)/n
css <- sum((x-meanx)^2)
sdx <- sqrt(css/(n-1))
meanx
sdx```
#概率函數(shù)
生成-3到3的31個(gè)值的序列
x <- pretty(c(-3,3),30)
密度函數(shù)d的正態(tài)分布norm
y <- dnorm(x)
yaxs表示y軸的畫軸方法,i表示刻度線都在數(shù)據(jù)范圍內(nèi)部
plot(x,y,type="l",xlab="NormalDeviate",ylab = "Density",yaxs="i")
通過指定隨機(jī)數(shù)種子躯概,可以再現(xiàn)以前的結(jié)果
set.seed(1234)
runif()函數(shù)生成0到1之間的均勻分布的隨機(jī)數(shù)
runif(5)
生成多元正態(tài)數(shù)據(jù)
library(MASS)
options(digits = 3)
設(shè)置隨機(jī)數(shù)種子登钥,以便再現(xiàn)結(jié)果
set.seed(1234)
指定均值向量
mean <- c(230.7,146.7,3.6)
指定方差-協(xié)方差矩陣(相關(guān)矩陣)
sigma <- matrix(c(15360.8,6721.2,-47.1,6721.2,4700.9,-16.5,
-47.1,-16.5,0.3),nrow=3,ncol=3)
mvrnorm produces one or more samples from the specified multivariate normal distribution
500是想要的樣本大小,返回結(jié)果是一個(gè)矩陣
mydata <- mvrnorm(500,mean,sigma)
轉(zhuǎn)化成數(shù)據(jù)框
mydata <- as.data.frame(mydata)
names(mydata) <- c("y","x1","x2")
dim(mydata)
head(mydata,n=10)```
字符處理函數(shù)
#paste()連接字符串,分隔符為seq
paste("x",1:3,"a",sep = "_")
#rep(x,n)將x重復(fù)n次,將1:3這個(gè)向量重復(fù)兩次
y <- rep(1:3,2)
#將選取n+1個(gè)等間距的整數(shù)值娶靡,將一個(gè)連續(xù)型變量x分隔成n個(gè)區(qū)間,畫圖常用
pretty(c(-3,3),30)
#將函數(shù)應(yīng)用于矩陣和數(shù)據(jù)框
a <- 5
sqrt(a)
b <- c(1.243,5.345,2.99)
round(b)
c <- matrix(runif(12),nrow=4)
c
log(c,base = 2)
mean(c)
#apply()函數(shù)牧牢,可以將任意函數(shù)應(yīng)用到矩陣,數(shù)組姿锭,數(shù)據(jù)框的任何維度上
#apply(x,MARGIN,FUN),MARGIN=1表示行塔鳍,MARGIN=2表示列
apply(c,1,mean)
#按列計(jì)算均值
apply(c,2,mean)
#計(jì)算截尾均值,基于中間20%的數(shù)據(jù)呻此,最高和最低的40%將被忽略
apply(c,2,mean,trim=0.4)```
#處理學(xué)生成績
包括成績變量的標(biāo)準(zhǔn)化轮纫,給出評分,名字排序
options(digits = 2)
Student <- c("John Davis","Angela Williams","Bullwinkle Moose","Kevin Du","Janice MarkHammer",
"Cheryl Cushing","Reuven Ytzrhak","Greg Knox","Joel England","Mary Rayburn")
Math <- c(502,600,412,634,495,512,410,625,573,522)
Science <- c(95,99,80,98,75,85,80,95,89,86)
English <- c(25,22,18,26,28,15,30,27,18,15)
roster <- data.frame(Student,Math,Science,English,stringsAsFactors = FALSE)
scale進(jìn)行數(shù)據(jù)的標(biāo)準(zhǔn)化焚鲜,針對每一列
z <- scale(roster[,2:4])
對每一行求平均值
score <- apply(z,1,mean)
然后將score列和roster合并,橫向合并掌唾,添加列
roster <- cbind(roster,score)
計(jì)算分位數(shù),0.8等作為分位點(diǎn)
y <- quantile(score,c(0.8,0.6,0.4,0.2))
建立新變量,score >= y[1]將返回一個(gè)logical向量,變量的重編碼
roster$grade[score >= y[1]] <- "A"
roster$grade[score < y[1] & score >= y[2]] <- "B"
roster$grade[score < y[2] & score >= y[3]] <- "C"
roster$grade[score < y[3] & score >= y[4]] <- "D"
roster$grade[score < y[4]] <- "F"
開始處理學(xué)生姓名
strsplit函數(shù)分割字符向量x中的元素,返回一個(gè)列表忿磅,有10個(gè)成分糯彬,每個(gè)有兩項(xiàng)
name <- strsplit((roster$Student)," ")
"["也是個(gè)函數(shù),"["(x,2)表示提取x向量中的第二個(gè)元素
lastname <- sapply(name,"[",2)
firstname <- sapply(name,"[",1)
roster[,-1]表示去除第一列
roster <- cbind(firstname,lastname,roster[,-1])
order返回一個(gè)排序后的行索引值向量
roster <- roster[order(firstname,lastname),]
roster <- roster[order(-score),]```
程序控制結(jié)構(gòu)
for(i in 1:10) print("hello world")
i<-10
while(i>0){print("hello");i<-i-1}
grade <- "love"
if(!is.factor(grade)) grade<-as.factor(grade) else print("grade is already a factor")
#ifelse結(jié)構(gòu)
score<-4
ifelse(score>2,print("passed"),print("failed"))
outcome <- ifelse(score > 2,"passed","failed")
#switch結(jié)構(gòu)
#根據(jù)i的值葱她,選擇后面執(zhí)行哪條語句
fellings <- c("sad","afraid")
for(i in fellings)
print(
switch(i,
happy="i am glad you are happy",
afraid="there is nothing to fear",
sad="cheer up",
angry="calm down now")
)```
#函數(shù)
mystats <- function(x,parametric=TRUE,print=FALSE){
if(parametric){
#參數(shù)統(tǒng)計(jì)量撩扒,均值和標(biāo)準(zhǔn)差
center <- mean(x);
spread <- sd(x);
}else{
#非參數(shù)統(tǒng)計(jì)量,中位數(shù)和絕對中位差
center <- median(x);
spread <- mad(x);
}
if(print & parametric){
cat("Mean=",center,"\n","SD=",spread,"\n")
}else if(print & !parametric){
cat("Median=",center,"\n","MAD=",spread,"\n")
}
生成一個(gè)列表吨些,name1=object1
result <- list(center=center,spread=spread)
return(result)
}
set.seed(1234)
Density,distribution function,quantile(分位數(shù))function and random generation for the normal
distribution with mean equal to mean and standard deviation equal to sd.
x<-rnorm(500)
y <- mystats(x)
返回的y是一個(gè)列表
y$center;y$spread;y[1];y[2]
y <- mystats(x,parametric = TRUE,print = TRUE)
y```
一個(gè)switch函數(shù)
mydate <- function(type="long"){
switch(type,
#%A是非縮寫星期名却舀,%B非縮寫月份
long = format(Sys.Date(),"%A %B %d %Y"),
short = format(Sys.Date(),"%Y-%m-%d"),
cat(type,"is not a recognized type\n")
)
}
mydate("long")
mydate("short")
mydate("middle")```
#轉(zhuǎn)置矩陣
cars <- mtcars(1:5,1:4)
t(cars)```
整合數(shù)據(jù)
options(digits = 3)
attach(mtcars)
#將數(shù)據(jù)折疊(整合),by中的變量必須在list中锤灿,哪怕只有一個(gè)變量挽拔,函數(shù)可以使用自定義函數(shù)
aggdata <- aggregate(mtcars,by=list(Group.cyl=cyl,Group.gear=gear),FUN = mean,na.rm=TRUE)
aggdata
detach(mtcars)```