【问题标题】:Reading a CSV file in R in a Function在函数中读取 R 中的 CSV 文件
【发布时间】:2015-07-17 14:43:26
【问题描述】:

我有一个问题,我似乎无法在网上任何地方找到答案。如果它已经被回答,我很抱歉,但是这里有。我在 R 中编写了一个脚本,它将为我完成预测过程,并根据交叉验证和其他标准返回最佳点预测。我想将此脚本保存为一个函数,这样我就不必每次去预测时都使用完整的脚本。我的脚本的基本设置如下:

output <- read.csv("C:/Users/data.csv", header = T)
colnames(output)
month_count = length(output[,1]) ##used in calculations throughout code
current_year = output[1,1]
current_month = output[1,2]
months = 5 #months to forecast out


m = 0
data <- ts(output[,3][c(1:(month_count-m))],
frequency = 12, start = c(current_year,current_month))
#runs all the other steps from here on

我正在编写的函数看起来像这样,它接受各种输入,然后运行脚本并打印回我的预测

forecastMe = function(sourcefile,months,m)
  {
            #runs the data prints out the result
  }

我遇到的问题是我希望能够在函数中输入目录和文件名,例如 C:/Users/documents/data1.csv (对于源文件部分),然后在我的 R 脚本的这一步。

output <- read.csv("C:/Users/sourcefile.csv", header = T)

我似乎找不到让它正确执行的方法。有什么想法或建议吗?

【问题讨论】:

  • 您遇到的具体问题是什么?我在这里没有发现任何问题。
  • 所以我想运行这样的函数 forecastMe(C:/users/documents/data.csv, 5, 10),但它不会将第一个字符串放入 read.csv 行稍后的。我是否应该创建一行,例如 file = "c:/users/documents/data.csv",然后将其作为 forecastMe(file,5,10) 运行?
  • 只需在函数体中将"C:/Users/data.csv" 替换为sourcefile,然后删除monthsm 的声明,因为您将它们传递给函数调用。
  • 所以现在可以正常工作了,但我现在收到错误 ts(x) 中的错误:对象不是矩阵

标签: r forecasting


【解决方案1】:

所以...

function(sourcefile, etc) {
  output <- read.csv(sourcefile, header = T)
  etc
}

……那个?我真的不明白你在问什么。

【讨论】:

    【解决方案2】:

    你快到了。你所要做的就是用你想传递给函数的变量名替换你的常量,并删除你不再需要的声明。

    forecastMe = function(sourcefile,months,m)   {
    
         output <- read.csv(sourcefile, header = T)
         colnames(output)
         month_count = length(output[,1]) ##used in calculations throughout code
         current_year = output[1,1]
         current_month = output[1,2]
    
         data <- ts(output[,3][c(1:(month_count-m))],
         frequency = 12, start = c(current_year,current_month))
         #runs all the other steps from here on
      }
    

    【讨论】:

    • 所以这基本上就是我现在要做的,但我遇到的问题是预测模型 ar.ols() 的错误。当我像我设置的那样通过函数读取数据时,它给了我错误 ts(x) 中的错误:'ts' 对象必须有一个或多个观察值或另一个 ts(x) 中的错误:对象不是一个矩阵..我正在使用的所有其他预测方法,例如 Arima、ets、holtwinters。
    • 所有其他预测方法都有效*,但 ar.ols 给我带来了问题
    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 2017-02-20
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    相关资源
    最近更新 更多