R - saemixData 函数在函数环境 "Error in file(file, "rt") 中找不到数据:无法打开连接"

R - saemixData function do not find data in a function environment "Error in file(file, "rt") : cannot open the connection"

在 R(版本 3.3.2)中,当我在函数内部使用函数 saemixData 时,出现错误 "Error in file(file, "rt") : cannot open the connection"。当 sim 在函数环境中时,就好像 saemixData 找不到 dataframe sim 一样。当代码在函数 f 之外 运行 时,或者当 sim 在全局环境中时,代码运行良好......这似乎是函数 saemixData 的错误,你有解决方案吗?

谢谢!

rm(list=ls())
library(saemix)  # saemix_2.1.tar.gz


f=function(){

    sim = data.frame(patient=c(1,1,1,2,2,2),
                          time=c(1,4,8,1,4,8),
                          HBA1C_obs=c(9,8,7,8,7.5,6))   

    saemix.data <- saemixData(name.data       = sim,
                              name.group      = "patient",
                              name.predictors =  c("time"),
                              name.response   = "HBA1C_obs")  

    saemix.data
}


f()

# Reading data from file sim 
# Error in file(file, "rt") : cannot open the connection
# Error in read(x) : 
#   The file sim does not exist. Please check the name and path. 

我也遇到了同样的问题。作为解决方法,您可以使用双箭头从函数内部将 sim 分配给全局环境:

sim <<- data.frame(patient=c(1,1,1,2,2,2),
                   time=c(1,4,8,1,4,8),
                   HBA1C_obs=c(9,8,7,8,7.5,6))

但这只是一个糟糕的修复,因为它会在每次调用该函数时覆盖全局环境中的任何 sim 对象。

是的,我知道这个问题,您可以将其归结为我对 R 环境问题的理解不足。我想要一个可以接受环境中的对象和磁盘上的文件的函数。对此我感到非常抱歉,如果有人有更好的函数编码方法 saemix.data 请随时发送!

另一种解决方法是将数据写入临时文件,但如果文件很大,这显然效率低下:

f=function(){
    sim = data.frame(patient=c(1,1,1,2,2,2),
                      time=c(1,4,8,1,4,8),
                      HBA1C_obs=c(9,8,7,8,7.5,6))
    tempname<-tempfile()
    write.table(sim,tempname,quote=F,col.names=T)
    saemix.data <- saemixData(name.data       = tempname,
                          name.group      = "patient",
                          name.predictors =  c("time"),
                          name.response   = "HBA1C_obs")
    saemix.data
}

f()

艾曼纽