1. 基本函数
用ls()
函数可以查看当前工作空间保存的变量和函数,用rm()
函数可以剔除不想要的对象.
ls()
可以指定一个pattern
参数,此参数定义一个匹配模式,只返回符合模式的对象名.模式格式是UNIX
中grep
的格式.比如,
ls(pattern="tmp[.]")
可以返回所有以“tmp.”
开头的对象名.
rm()
可以指定一个名为list的参数给出要删除的对象名,所以
rm(list=ls(pattern=“tmp[.]”))`
可以删除所有以“tmp.”
开头的对象名.
fix
将打开一个编辑窗口显示函数的定义,修改后关闭窗口函数就被修改了.fix()调用的编辑程序缺省为记事本,可以用“options(editor="编辑程序名")”
来指定自己喜欢的编辑程序.
2. 作用域
与c语言类似,全局变量与局部变量的关系
x = list(1, "abc")
x
f =function(x) {x[[2]] <- "!!" ;x}
f(x)
x
x = 2
f = function() {print(x) ; x= 20; print(x) }
f()
[1] 2
20
x
[1] 2
这个例子中原来有一个变量x值为2,函数中为变量x赋值20,但函数运行完后原来的x值并未变化.但是也要注意,函数中的显示函数调用时局部变量x还没有赋值,显示的是全局变量x 的值.这是R编程比较容易出问题的地方:你用到了一个局部变量的值,你没有意识到这个局部变量还没有赋值,而程序却没有出错,因为这个变量已有全局定义.
3. 例子
3.1 中位数和均值的比值函数
median.mean.ratio <- function(x){
return(median(x)/mean(x))
}
3.2 设银行年利率为2.52%。将10000元钱存入银行,问至少多长时间会连本带利翻一番?4.14 呢?
count <- function(money, i){
year <- 1
money0 <- money
while(money<=2*money0){
money <- money * (1 + i)^year
year <- year + 1
}
year
}
3.3 考虑一个简单的银行存取款系统
#有错误,全局变量。
open.account=function(total){
total <- 0
list(
deposit=function(amount) {
if (amount<=0)
stop("Deposits must be positive!\n")
total <<-total+amount
cat(amount,"deposited. Your balance is", total,"\n\n")
},
withdraw=function(amount) {
if(amount > total)
stop ("Sorry, you don't have that much money!\n")
total<<- total-amount
cat(amount, "withdrawn. Your balance is",total,"\n\n")
},
balance=function(){
total<<-total;
cat("Your balance is", total,'\n\n')
}
)
}
total <- 100;
client <- open.account(total);
client $ deposit (20);
client $ withdraw (200);
client $ withdraw (40);
client $ balance ( );
3.4 : score.txt(tab分隔的文本文档)文档存放了某次选秀节目10位选手的姓名和6个评委的打分记录,根据比赛规则,对每位选手的最终成绩计算方法为:去掉一个最高分,去掉一个最低分,然后剩下的求平均。请编写一个程序,将每位选手的最终成绩存放在final.score中,要求final.score的结果里面的第一列是选手的姓名,第二列是他的最终成绩,第三列是名次。
setwd('E:\\github\\Rlearning-Xie')
score <- read.table("score.txt",header=T,sep='\t')
head(score)
countscore <- function(df){
final.score <- (sum(df)-max(df)-min(df))/4
}
finalscore <- apply(as.data.frame(score)[,-1],1,countscore)
finalscore<- rbind(as.character(as.data.frame(score)[,1]),finalscore ,order(finalscore))
names(finalscore) <- c("names","score","order")
t(finalscore)
[1,] "李芳芳" "9.65" "6"
[2,] "秦娅兰" "9.575" "8"
[3,] "朱萱" "9.775" "10"
[4,] "赵婷婷" "9.475" "4"
[5,] "庄丽" "9.55" "5"
[6,] "陈飞霞" "9.225" "2"
[7,] "诸葛琳" "9.6" "7"
[8,] "曲菁" "9.25" "9"
[9,] "张惠" "9.625" "1"
[10,] "刘洁瑜" "9.4" "3"