0610 14:26
统计函数
mean(x, trim=0.05, na.rm=TRUE)
0.05截尾平均数函数
- 其他有用统计函数
函数 | 描述 |
---|---|
median (x) | 中位数 |
mad (x) | 绝对中位差 |
quantile (x, prob) | 求分位数 |
数值和字符处理函数
函数 | 描述 |
---|---|
nchar (x) | 计算x中的字符数量 |
substr(x, start, stop) | 提取或替换一个字符向量中的子串 |
- | x<-"abcdef" |
- | substr(x,2,4) 返回为"bcd" |
- | substr(x,2,4)<-"22222" (x就会变成“a222ef") |
grep(pattern, x, ignore.case=F, fixed=F) | 在x中搜索某种模式,fixed=TRUE,则该模式为一个文本字符串。grep("A",c("b","A","c"),fixed=TRUE)返回值为 2 |
sub(pattern, replacement, x, ignore.case=FALSE, fixed=FALSE) | 在 x 中搜索 pattern,并以文本 replacement 将其替换。若 fixed=FALSE,则 pattern 为一个正则表达式。若 fixed=TRUE,则 pattern 为一个文本字符串。sub("\s",".","Hello There")返回值为 Hello.There。注意,"\s"是一个 用来查找空白的正则表达式;使用"\s"而不用""的原因是,后者是 R 中的转义字符 |
strsplit(x, split, fixed=FALSE) | 在 split 处分割字符向量 x 中的元素。========= y <- strsplit("abc", "")将返回一个含有 1 个成分、3 个元素的列表,包含 的内容为"a" "b" "c"。 unlist(y)[2]和 sapply(y, "[", 2)均会返回"b" |
paste(..., sep="") | 连接字符串,分隔符为 sep。 ---------------paste("x", 1:3, sep="")返回值为 c("x1", "x2", "x3") paste("x",1:3, sep="M")返回值为 c("xM1","xM2" "xM3") |
有关R的正则表达式Github: http://yphuang.github.io/blog/2016/03/15/regular-expression-and-strings-processing-in-R/
正则表达式还是比较繁琐的。需要另外专门总结一下。
- 将函数用于矩阵和数据框
apply( )
apply(x, Margin, Function)
Margin=1 行
Margin=2 列
> mydata <- matrix(rnorm(30), nrow=6)
> mydata
[,1] [,2] [,3] [,4] [,5]
[1,] 1.1502551 -0.6367003 -0.05004926 1.77287949 -0.3606222
[2,] 1.2278937 -2.1059314 0.11102871 0.42655066 -0.8879844
[3,] 0.1521032 -0.6462584 0.47547105 -0.09447017 -0.9464166
[4,] -0.5230838 0.9867934 -0.93900390 -1.11659543 -0.2199116
[5,] -1.1015934 -0.7549001 -0.77404562 -0.08743515 0.3422201
[6,] -0.8797303 1.5652049 -0.42355847 0.39252609 0.9699241
> apply(mydata, 1, mean) # 求行平均
[1] 0.3751526 -0.2456886 -0.2119142 -0.3623603 -0.4751508 0.3248733
> apply(mydata, 2, mean) # 求列平均
[1] 0.004307407 -0.265298651 -0.266692917 0.215575915 -0.183798399
> apply(mydata, 2, mean, trim=.4)
[1] -0.1854903 -0.6414793 -0.2368039 0.1525455 -0.2902669
例题
将学生的各科考试成绩组合为单一的成绩衡量指标,基于相对名次 (前20%、下20%、等等)给出从A到F的评分,根据学生姓氏和名字的首字母对花名册进行排序。
- 组织好dataframe
options(digits=2)
Student <- c("John Davis", "Angela Williams", "Bullwinkle Moose",
"David Jones", "Janice Markhammer", "Cheryl Cushing",
"Reuven Ytzrhak", "Greg Knox", "Joel England",
"Mary Rayburn")
Math <- c(502, 600, 412, 358, 495, 512, 410, 625, 573, 522)
Science <- c(95, 99, 80, 82, 75, 85, 80, 95, 89, 86)
English <- c(25, 22, 18, 15, 20, 28, 15, 30, 27, 18)
roster <- data.frame(Student, Math, Science, English,
stringsAsFactors=FALSE)
- 由于不同科目评价标准不同,所以需要将数据标准化处理。并且新添一组评价,为三科标准化处理后的平均数。
z <- scale(roster[,2:4])
score <- apply(z, 1, mean)
roster <- cbind(roster, score)
- 根据群体成绩的从高到低的0.8,0.6,0.4,0.2,将grade设置为A,B,C,D,F
y<-quantile(score,c(.8,.6,.4,.2))
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"
用if,else来试一下
if(score>=y[1]){
roster$grade<-"A"
}else if(score>=y[2]){
roster$grade<-"B"
}else if(score>=y[3]){
roster$grade<-"C"
}else if(score>=y[4]){
roster$grade<-"D"
}else{
roster$grade<-"F"
}
貌似哪里出问题了。。。。
4.提取姓氏和名字
names<-strsplit(roster$Student," ")
lastname<-sapply(names,"[",2)
firstname<-sapply(names,"[",1)
roster<-cbind(firstname,lastname,roster)
roster<-roster[,-3]
5.根据姓氏和名字字母排序
roster<-roster[order(lastname,firstname),]
head(roster)
> head(roster)
firstname lastname Math Science English score grade
5 Janice Markhammer 495 75 20 -0.63 D
6 Cheryl Cushing 512 85 28 0.35 C
2 Angela Williams 600 99 22 0.92 A
4 David Jones 358 82 15 -1.16 F
10 Mary Rayburn 522 86 18 -0.18 C
8 Greg Knox 625 95 30 1.34 A
控制流
- for结构
重复执行一条命令,直到某个变量不在序列seq里为止。
for (var in seq) statment
for (i in 1:10) print("hello")
- while
重复执行一条命令,直到执行条件不为真为止。
while(cond) statment
i<-10
while (i>0) {print ("hello") ; i<-i-1}
- if-else
if (is.character(grade)) grade <- as.factor(grade)
if (!is.factor(grade)) grade <- as.factor(grade)
else print("Grade alreadyis a factor")
- switch
feelings <- c("sad", "afraid")
for (i in feelings)
print(
switch(i,
happy = "I am glad you are happy",
afraid = "There is nothing to fear",
sad = "Cheer up",
angry = "Calm down now"
)
)
Function
myfunction <- function(arg1, arg2, ... ){ statements
return(object)
}
例1. 编写一个函数,用来计算数据对象的集中趋势和散布情况。此函数应当可以选择性 地给出参数统计量(均值和标准差)和非参数统计量(中位数和绝对中位差)。结果应当以一个 含名称列表的形式给出。另外,用户应当可以选择是否自动输出结果。除非另外指定,否则此函 数的默认行为应当是计算参数统计量并且不输出结果。
0611 11:00
拆解一下过程
- 函数x,默认是参数统计量(
parametric=TRUE, print=FALSE
) - 如果
parametric=TRUE
,则计算均值mean
,标准差sd
,如果是非参数统计量,就计算中央值median
,绝对中为差mad
。 - 如果指定输出
print=TRUE
,就分两种情况。
a.parametric=TRUE,
cat ("Mean= ", center, "\n", "SD=", spread, "\n")
b.!parametric=TRUE,
cat("Median=", center, "\n", "MAD=", spread, "\n")
- 以列表的形式输出
抄正确答案很简单,但是不能发现问题。写自己写着试了一下,然后果然出问题了。
- 错误
if(parametric){
+ center<-mean(x),spread=sd(x)
エラー: 予想外の ',' です in:
" if(parametric){
center<-mean(x)," #不能是逗号,得用分号。
- 修正版
mystats<-function(x,parametric=TRUE,print=FALSE){
if(parametric){
center<-mean(x);spread=sd(x)
} else {
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")
}
result <- list(center=center, spread=spread)
return(result)
}
- 测试一下
> set.seed(1234)
> x <- rnorm(500)
> y <- mystats(x)
> y <- mystats(x, parametric=FALSE, print=TRUE)
Median= -0.021
MAD= 1
例2.函数
mydate()
可让用户选择输出当天日期 的格式。在函数声明中为参数指定的值将作为其默认值。在函数mydate( )
中,如果未指定type
, 则long
将为默认的日期格式
mydate<-function(type="long"){
switch(type,
long=format(Sys.time(),"%A %B %d %Y"),
short=format(Sys.time(),"%m-%d-%y"),
cat(type, "is not a recognized type \n")
)
}
- 测试
> mydate()
[1] "Monday July 14 2014"
> mydate("medium")
medium is not a recognized type
数据整合
aggregate(x, by, FUN)
根据by的条件重新分组,并根据FUN求值。
其中by必须是一个列表,by=list( )
> 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
在结果中,Group.1表示汽缸数量(4、6或8),Group.2代表挡位数(3、4或5)。举例来说, 拥有4个汽缸和3个挡位车型的每加仑汽油行驶英里数(mpg)均值为21.5。
reshape2
> mydata
ID Time X1 X2
1 1 1 5 6
2 1 2 3 5
3 2 1 6 1
4 2 2 2 4
> md <- melt(mydata, id=c("ID", "Time"))
> md
ID Time variable value
1 1 1 X1 5
2 1 2 X1 3
3 2 1 X1 6
4 2 2 X1 2
5 1 1 X2 6
6 1 2 X2 5
7 2 1 X2 1
8 2 2 X2 4
暂时还没有hint这个功能用在什么地方。。。
0611 14:21
以上
网友评论