【问题标题】:R function displays object "obser" but won't write.CSVR函数显示对象“观察者”但不会写.CSV
【发布时间】:2017-06-21 12:07:11
【问题描述】:

我的代码工作并在屏幕上为print(obser) 显示正确的值,但不会写入.csv,当我尝试str(obser) 时,它给出了错误object 'obser' not found。我尝试了各种在线帮助和书籍,并且功能正确编写。

如果不是在 RStudio 的控制台中运行函数,而是在脚本屏幕中逐行运行,那么会创建 csv 吗?

complete <- function(directory= "specdata", id = 1:332){ 

    # directory <- "specdata" 
    # id <- 1:332

    files_list <- list.files(path=directory,full.names=T)[id]
    NumOfFiles <- length(files_list) 
    obser <- data.frame() 
    indivFile <-data.frame()
    nobserv <- vector(mode= "integer", length = NumOfFiles) 

    for (i in 1:NumOfFiles){
        indivFile <- read.csv(files_list[i]) # read data file into df  inc NA's
        indivFile <- na.omit(indivFile) # removes NA prev file
        x <- nrow(indivFile[1]) 
        nobserv[i] <- x
    } 

    x_name <-"ID"
    y_name <-"nobs"
    obser <- data.frame(id, nobserv)

    return(obser) # object returned 
    print(obser)
    wd <- getwd()
    setwd(wd)
    write.csv(obser, file="Observations2.csv")
} 

【问题讨论】:

  • setwd(wd &lt;- getwd()) 没有在代码中添加任何内容

标签: r export-to-csv


【解决方案1】:

尝试保存从函数返回的对象。尔格:

output<-complete("specdata",id=1:332)
write.csv(output,"Observations2.csv",row.names=F)

【讨论】:

  • 试了一下,以为我没有运行函数只是定义了它,但仍然没有数据文件输出
  • 抱歉我的错误,我意识到问题出在哪里......我首先确实混淆了函数定义并在脚本中运行函数。
猜你喜欢
  • 2021-12-24
  • 2021-10-20
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
  • 2019-11-02
  • 2015-12-30
  • 2022-11-17
  • 1970-01-01
相关资源
最近更新 更多