[英]i don't think i understand function enclosures
I'm trying to package some code I use for data analysis so that other workers can use it. 我正在尝试打包一些用于数据分析的代码,以便其他工作人员可以使用它。 Currently, I'm stuck trying to write a simple function that imports data from a specific file type generated by a datalogger and trims it for use by other functions.
当前,我一直试图编写一个简单的函数,该函数从数据记录器生成的特定文件类型导入数据,并对其进行修剪以供其他函数使用。 Here's the code:
这是代码:
import<-function(filename,type="campbell",nprobes){
if (filename==TRUE){
if (type=="campbell"){
message("File import type is from Campbell CR1000")
flux.data<<-read.table(filename,sep=",",header=T,skip=1)
flux.data<<-flux.data[,-c(1,2)];flux.data<<-flux.data[-c(1,2),]
if (nprobes=="missing"){
nprobes<-32
}
flux.data<<-flux.data[,c(1:nprobes)]
flux.data.names<<-colnames(flux.data) #Saves column names
}
}
}
Ideally, the result would be a dataframe/matrix flux.data
and a concomittant vector/list of the preserved column headers flux.data.names
. 理想情况下,结果将是一个数据帧/矩阵
flux.data
和一个保留列标题flux.data.names
的伴随向量/列表。 The code runs and the function executes without errors, but the outputs aren't preserved. 代码运行并且函数执行没有错误,但是没有保留输出。 I usually use
<<-
to get around the function enclosure but its not working in this case - any suggestions? 我通常使用
<<-
绕过功能外壳,但在这种情况下不起作用-有什么建议吗?
I think the real problem is that I don't quite understand how enclosures work, despite a lot of reading... should I be using environment
to assign environments within the function? 我认为真正的问题是,我不太,了解机箱的工作,尽管大量的阅读......我应该使用
environment
分配的功能范围内的环境?
User joran answered my question in the comments above: 用户joran在上面的评论中回答了我的问题:
The critical issue was just in how the function was written: the conditional at the start ( if filename==TRUE
) was intended to see if filename was specified, and instead was checking to see if it literally equaled TRUE
. 关键问题在于函数的编写方式:开头的条件(
if filename==TRUE
)旨在查看是否指定了filename,而是检查其字面上是否等于TRUE
。 The result was the conditional never being met, and no function output. 结果是从不满足条件,并且没有函数输出。 Here's what fixed it:
修复问题的方法如下:
import<-function(filename,type="campbell",nprobes){
if (exists(filename){
if (type=="campbell"){
#etc....
Another cool thing he pointed out was that I didn't need the <<-
operator to utilize the function output and instead could write return(flux.data)
. 他指出的另一件很酷的事情是,我不需要
<<-
运算符来利用函数输出,而是可以编写return(flux.data)
。 This is a much more flexible approach, and helped me understand function enclosures a lot better. 这是一种更加灵活的方法,帮助我更好地了解了功能外壳。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.