【发布时间】:2018-03-28 15:02:55
【问题描述】:
如何在 R 中创建一个以向量为参数的函数 并上传多个由向量定义的范围的csv文件?
我做了这样的事情:
my_Funk <- function(x) {
## I am initialising function my_Funk that takes on one argument x
setwd("my_data")
## I am setting working directory to my_data
temp <- list.files(pattern = "*.csv")
## I store the list of the *.csv files in the vector temp
for (i in x) assign(temp[i], read.csv(temp[i]))
## I read only specified portion of the *.csv files into the R environment
## The portion defined by the vector x
}
当我将函数上传到全局环境中时
然后用my_Funk(1:5) 调用它 - 没有任何反应。
我也没有看到任何 temp 变量或任何 csv 文件
如果我一个一个地执行我的函数的一部分,它工作得很好 但是,它不能作为一个整体工作
【问题讨论】:
-
任何在函数内部创建但未从函数返回的变量在函数运行完成后消失。您的函数应该返回一个包含您希望加载的 data.frames 的列表,您可以保存该列表以供以后使用。避免using assign()。