R语言学习笔记 -- R程序与函数《R语言入门》

注:参考书籍《R语言入门》
程序:
一般,R程序都会以.R的扩展名、ASCII格式保存。

#程序示例:
layout(matrix(1:3 , 3 , 1))
data <- read.table("Swal.dat")
plot(data$V1 , data$V2 , type = "1")
title(data$V1 , data$V2 , type = "1")
title("wren")
data <- read.table("Dunn.dat")
plot(data$V1 , data$V2 , type = "1")
title("dunnock")


##利用向量的概念,可以改进上述程序,展示如下:
layout(matrix(1:3 , 3 , 1)) #分割图形
species <- c("aa" , "bb" , "dd")
file <- c("aa.dat" , "bb.dat" , "dd.dat")
for (i in 1:length(species)) {
  data <- reda.table(file[i])#读入数据
  plot(data$V1 , dadta$V2 , type = "1")
  title(species[i] )#添加标题
  }
  

保存程序文件,使用命令如下:
>source("myfile.R") #即保存在文件夹myfile中

编写函数:

  1. 在函数内部 , 无需进行变量声明;
  2. 函数执行时,词语作用域(lexical scoping)决定一个对象相对一个函数时局部还是全局的。简单地说,和C++中的局部、全局变量差不多 。但是 ,如果变量x没有在自定函数中声明 并且 被直接调用 , 那么R将会在封装环境中搜索该变量。是一种逐层搜索,直到全局环境。
  3. 调用函数时,传参也和C++大体相同
#示例
myfun <- function(s , d){
  data <- read.table(d) #读取数据
  plot(data$V1 , data$V2 , type = "l")
  title(s)
}

执行函数:
执行前,函数必须载入内存。
1.若 函数保存在文本文件 中,可以使用命令source()载入;
5. 若希望能够在启动R时就被载入,可以把他们保存在工作目录下的文件.RData
6. 配置文件.Rprofile或是Rprofile

#执行上面的自定义函数,如下
layout(matrix(1:3 , 3 , 1))
myfun("aa" , "aa.dat")
myfun("bb" , "bb.dat")
myfun("dd" , "dd.dat")
#方法2,使用sapply函数
layout(matrix(1:3 , 3 , 1))
species <- c("aa" , "bb" , "dd")
file <- c("aa.dat" , "bb.dat" , "dd.dat")
sapply(species , myfun , file) 
发布了124 篇原创文章 · 获赞 30 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43448491/article/details/104138026