在基本數(shù)據(jù)管理中主要學(xué)習(xí)了數(shù)據(jù)框(data.frame)的基本操作坐昙,主要包括:簡單數(shù)據(jù)文件讀入鳖擒、創(chuàng)建/刪除變量(列)溉浙、行列的重命名、變量重編碼蒋荚、NA值簡單處理戳稽、數(shù)據(jù)選取等。
本節(jié)主要介紹一些數(shù)學(xué)統(tǒng)計函數(shù)和字符處理函數(shù)期升、數(shù)據(jù)整合與重塑等惊奇。
1、數(shù)學(xué)統(tǒng)計函數(shù)和字符處理函數(shù)
R中常用的數(shù)學(xué)函數(shù)如下播赁,這些函數(shù)都具有廣播性:
函數(shù) | 描述 |
---|---|
abs(x) | 取絕對值 |
sqrt(x) | 取平方根 |
ceiling(x) | 不小于x的最小整數(shù)颂郎,如ceiling(3.5)返回4 |
floor(x) | 不大于x的最大整數(shù),floor(3.5)返回3 |
trunc(x) | 取整數(shù)部分容为,如trunc(3.5)返回3 |
round(x, digits=n) | 四入五入到指定位數(shù)乓序,如round(3.458, digits=2)返回值為3.46 |
signif(x, digits=n) | 四舍五入到指定有效數(shù)字位數(shù),如signif(3.458, digits=2)返回值3.5 |
cos(x)坎背、sin(x)替劈、tan(x)、acos(x)得滤、asin(x)陨献、atan(x)、cosh(x)懂更、sinh(x)眨业、acosh(h)等 | 三角函數(shù) |
log(x, base=n) | 以n為底對x取對數(shù)急膀,其中l(wèi)og(x)為自然對數(shù),log10(x)為常用對數(shù) |
exp(x) | 以e為底的指數(shù)函數(shù) |
常用統(tǒng)計函數(shù)如下所示龄捡,其中大部分函數(shù)都擁有重要參數(shù)脖阵,如mean(x,trim=0.05,na.rm=TRUE)
表示去除首尾5%極值和所有缺失值后的算術(shù)平均數(shù)。使用墅茉?func
可查看相應(yīng)函數(shù)用法。
函數(shù) | 描述 |
---|---|
mean(x) | 求平均數(shù) |
median(x) | 中位數(shù) |
sd(x) | 標(biāo)準(zhǔn)差 |
var(x) | 方差 |
mad(x) | 絕對中位差(median absolute deviation) |
quantile(x, probs) | 求分位數(shù)呜呐。其中x為代求分位數(shù)的數(shù)值型向量就斤,probs為[0,1]間的概率值組成的數(shù)值向量,如quantile(x, c(0.3,0.8)) |
range(x) | 求值域 |
sum(x) | 求和 |
diff(x, lag=n) | 滯后差分蘑辑,lag指定滯后幾項洋机,默認(rèn)為1 |
min(x) | 最小值 |
max(x) | 最大值 |
scale(x, center=TRUE, scale=TRUE) | 為數(shù)據(jù)對象按列進(jìn)行中心化(center=TRUE)或標(biāo)準(zhǔn)化(center=TRUE, scale=TRUE) |
默認(rèn)情況下 ,函數(shù)scale()對矩陣或數(shù)據(jù)框的指定列進(jìn)行均值為0洋魂,標(biāo)準(zhǔn)差為1的標(biāo)準(zhǔn)化绷旗。下面的例子簡單展示了scale的用法。
> student <- c('andy','lucy','mike','jacky');score <- c(88,92,67,75);df<-data.frame(student,score);df
student score
1 andy 88
2 lucy 92
3 mike 67
4 jacky 75
> scale(df$score)
[,1]
[1,] 0.6487087
[2,] 0.9946866
[3,] -1.1676756
[4,] -0.4757197
attr(,"scaled:center")
[1] 80.5
attr(,"scaled:scale")
[1] 11.56143
# 要進(jìn)行任意均值和標(biāo)準(zhǔn)差的標(biāo)準(zhǔn)化副砍,可用 scale(x)*SD + M, 其中SD表示標(biāo)準(zhǔn)差衔肢,M表示均值
> df <- transform(df, scale_score=scale(score)*10+50);df
student score scale_score
1 andy 88 56.48709
2 lucy 92 59.94687
3 mike 67 38.32324
4 jacky 75 45.24280
概率分布函數(shù)暫時還不太懂。下面是字符處理函數(shù)豁翎。
函數(shù) | 描述 |
---|---|
nchar(x) | 計算x中的字符數(shù)量 |
substr(x, start, stop) | 提取或替換一個字符向量的子串 |
grep(pattern, x, ignore.case=FALSE, fixed=FALSE) | 在x中搜索某種模式角骤。fixed=FALSE時表示pattern使用正則表達(dá)式,否則pattern僅表示字符串心剥。返回值為匹配的下標(biāo) |
sub(pattern, replacement, x, ignore.case=FALSE, fixed=FALSE) | 在x中搜索pattern邦尊,并以replacement將其替換。fixed用法與grep相同 |
strsplit(x, split, fixed=FALSE) | 以split為分隔符分割x优烧,返回一個列表 |
paste(...,sep="") | 以sep為連接符連接字符串 |
toupper(x) | 轉(zhuǎn)換為大寫 |
tolower(x) | 轉(zhuǎn)換為小寫 |
其他一些常用函數(shù)
函數(shù) | 描述 |
---|---|
length(x) | x長度 |
seq(from, to, by) | 生成一個序列 |
rep(x, n) | 生成一個x重復(fù)n次的向量 |
cut(x, n) | 將連續(xù)型變量x分割為有著n個水平的因子蝉揍,使用ordered_result=TRUE以創(chuàng)建一個有序型因子 |
pretty(x ,n) | 創(chuàng)建美觀的分割點。通過選取n+1個等間距的取整值畦娄,將一個連續(xù)型變量x分割為n個區(qū)間又沾。繪圖常用 |
cat(..., file="filename", append=FALSE) | 連接...中的對象,并將其輸出到屏幕上或文件中(如果聲明了的話) |
2熙卡、一個數(shù)據(jù)處理的例子
現(xiàn)有一些學(xué)生成績捍掺,需要對其做出整理做出一個綜合排序。例子來自R語言實戰(zhàn)再膳。
##### 生成數(shù)據(jù)
> math <- c(500,600,450,465,550,530,487,568,350,400)
> science <- c(90,98,95,86,84,99,75,80,76,74)
> english <- c(25,20,18,12,23,15,22,13,30,17)
> student<-c('john davis', 'angela willam', 'bull moose', 'david jones', 'janice mark', 'chery cushing', 'riven yark', 'greg knox', 'joel england', 'olaf halen')
> df <- data.frame(student, math, science, english, stringsAsFactors=FALSE);df
student math science english
1 john davis 500 90 25
2 angela willam 600 98 20
3 bull moose 450 95 18
4 david jones 465 86 12
5 janice mark 550 84 23
6 chery cushing 530 99 15
7 riven yark 487 75 22
8 greg knox 568 80 13
9 joel england 350 76 30
10 olaf halen 400 74 17
######由于各科成績的總分不同挺勿,將其標(biāo)準(zhǔn)化便于比較
> z <- scale(df[c(2:4)])
######取標(biāo)準(zhǔn)化后各科成績的平均值作為每個學(xué)生的綜合成績
> options(digits=2);df$score <- apply(z, 1, mean);df
student math science english score
1 john davis 500 90 25 0.519
2 angela willam 600 98 20 0.937
3 bull moose 450 95 18 0.064
4 david jones 465 86 12 -0.541
5 janice mark 550 84 23 0.407
6 chery cushing 530 99 15 0.373
7 riven yark 487 75 22 -0.240
8 greg knox 568 80 13 -0.246
9 joel england 350 76 30 -0.325
10 olaf halen 400 74 17 -0.947
#####新增變量grade使用ABCDF來表示成績,即重編碼
> df$grade[df$score>=y[4]] <- 'A';df$grade[df$score<y[4] & df$score>=y[3]]<-'B';df$grade[df$score>=y[2] & df$score<y[3]]<-'C'; df$grade[df$score<y[2]& df$score>=y[1]]<-'D';df$grade[df$score<y[1]]<-'F';df
student math science english score grade
1 john davis 500 90 25 0.519 A
2 angela willam 600 98 20 0.937 A
3 bull moose 450 95 18 0.064 C
4 david jones 465 86 12 -0.541 F
5 janice mark 550 84 23 0.407 B
6 chery cushing 530 99 15 0.373 B
7 riven yark 487 75 22 -0.240 C
8 greg knox 568 80 13 -0.246 D
9 joel england 350 76 30 -0.325 D
10 olaf halen 400 74 17 -0.947 F
#####拆分姓名
> name <- strsplit(df$student, " ")
> name
[[1]]
[1] "john" "davis"
[[2]]
[1] "angela" "willam"
[[3]]
[1] "bull" "moose"
[[4]]
[1] "david" "jones"
[[5]]
[1] "janice" "mark"
[[6]]
[1] "chery" "cushing"
[[7]]
[1] "riven" "yark"
[[8]]
[1] "greg" "knox"
[[9]]
[1] "joel" "england"
[[10]]
[1] "olaf" "halen"
#####將姓和名分別賦值給一個向量喂柒,然后將這兩個向量合并到數(shù)據(jù)框中
> lastname<-sapply(name, '[', 2); firstname<-sapply(name,'[',1);df<- cbind(firstname,lastname,df[,-1]);df
firstname lastname math science english score grade
1 john davis 500 90 25 0.519 A
2 angela willam 600 98 20 0.937 A
3 bull moose 450 95 18 0.064 C
4 david jones 465 86 12 -0.541 F
5 janice mark 550 84 23 0.407 B
6 chery cushing 530 99 15 0.373 B
7 riven yark 487 75 22 -0.240 C
8 greg knox 568 80 13 -0.246 D
9 joel england 350 76 30 -0.325 D
10 olaf halen 400 74 17 -0.947 F
#####使用firstname和lastname這兩項進(jìn)行排序
> df<-df[order(firstname,lastname),];df
firstname lastname math science english score grade
2 angela willam 600 98 20 0.937 A
3 bull moose 450 95 18 0.064 C
6 chery cushing 530 99 15 0.373 B
4 david jones 465 86 12 -0.541 F
8 greg knox 568 80 13 -0.246 D
5 janice mark 550 84 23 0.407 B
9 joel england 350 76 30 -0.325 D
1 john davis 500 90 25 0.519 A
10 olaf halen 400 74 17 -0.947 F
7 riven yark 487 75 22 -0.240 C
3不瓶、數(shù)據(jù)整合與重構(gòu)
使用函數(shù)t()
可以對數(shù)據(jù)框或者矩陣進(jìn)行轉(zhuǎn)置禾嫉。
> cars <- mtcars[1:5,1:4];cars
mpg cyl disp hp
Mazda RX4 21 6 160 110
Mazda RX4 Wag 21 6 160 110
Datsun 710 23 4 108 93
Hornet 4 Drive 21 6 258 110
Hornet Sportabout 19 8 360 175
> t(cars)
Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
mpg 21 21 23 21 19
cyl 6 6 4 6 8
disp 160 160 108 258 360
hp 110 110 93 110 175
使用R內(nèi)置函數(shù)aggregate(x ,by, FUN)
可以對數(shù)據(jù)進(jìn)行折疊(collapse,相當(dāng)于分組蚊丐,python pandas中g(shù)roupby熙参,F(xiàn)UN相當(dāng)于groupby后進(jìn)行的處理函數(shù))。by是一個變量名組成的列表(必須是列表)麦备,還可以為分組變量聲明自定義的名稱孽椰。FUN表示對每一個分組內(nèi)的數(shù)據(jù)進(jìn)行的處理方式。
> options(digits=3)
> attach(mtcars)
> aggdata <- aggregate(mtcars, by=list(cyl,gear),FUN=mean,na.rm=TRUE); aggdata
Group.1 Group.2 mpg cyl disp hp drat wt qsec vs am gear carb
1 4 3 21.5 4 120 97 3.70 2.46 20.0 1.0 0.00 3 1.00
2 6 3 19.8 6 242 108 2.92 3.34 19.8 1.0 0.00 3 1.00
3 8 3 15.1 8 358 194 3.12 4.10 17.1 0.0 0.00 3 3.08
4 4 4 26.9 4 103 76 4.11 2.38 19.6 1.0 0.75 4 1.50
5 6 4 19.8 6 164 116 3.91 3.09 17.7 0.5 0.50 4 4.00
6 4 5 28.2 4 108 102 4.10 1.83 16.8 0.5 1.00 5 2.00
7 6 5 19.7 6 145 175 3.62 2.77 15.5 0.0 1.00 5 6.00
8 8 5 15.4 8 326 300 3.88 3.37 14.6 0.0 1.00 5 6.00
> aggdata <- aggregate(mtcars, by=list(Group.cyl=cyl,Group.gear=gear),FUN=mean,na.rm=TRUE); aggdata
Group.cyl Group.gear mpg cyl disp hp drat wt qsec vs am gear carb
1 4 3 21.5 4 120 97 3.70 2.46 20.0 1.0 0.00 3 1.00
2 6 3 19.8 6 242 108 2.92 3.34 19.8 1.0 0.00 3 1.00
3 8 3 15.1 8 358 194 3.12 4.10 17.1 0.0 0.00 3 3.08
4 4 4 26.9 4 103 76 4.11 2.38 19.6 1.0 0.75 4 1.50
5 6 4 19.8 6 164 116 3.91 3.09 17.7 0.5 0.50 4 4.00
6 4 5 28.2 4 108 102 4.10 1.83 16.8 0.5 1.00 5 2.00
7 6 5 19.7 6 145 175 3.62 2.77 15.5 0.0 1.00 5 6.00
8 8 5 15.4 8 326 300 3.88 3.37 14.6 0.0 1.00 5 6.00
#####在這里mean表示對每一個組內(nèi)的數(shù)據(jù)去平均值凛篙,如分組(cyl=4, gear=3)所對應(yīng)的所有的mpg的均值為21.5
aggregate
可以對數(shù)據(jù)進(jìn)行簡單的整合黍匾,但要進(jìn)行更復(fù)雜的重構(gòu),可以使用reshape2包呛梆,但reshape2較難以理解锐涯。
參考:
R語言實戰(zhàn).