【问题标题】:Create a function that reads multiple csv files within the range defined by the argument of the function创建一个函数,在函数参数定义的范围内读取多个 csv 文件
【发布时间】: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()

标签: r csv


【解决方案1】:

您可以将数据存储在数据框列表中。这是一个例子。

# Get the files
temp <- list.files(pattern = "*.csv")
# Load and store your files in a list of data frame
data <- lapply(temp, function(x) read.csv(x, stringsAsFactors = FALSE)) # all the files are loaded
#or
data10 <- lapply(temp[1:10], function(x) read.csv(x, stringsAsFactors = FALSE)) # first 10 files are loaded


# So based on what your started, a function doing this could be
my_Funk <- function(id){
        setwd("my_data")
        temp <- list.files(pattern = "*.csv")
        data <- lapply(temp[id], function(x) read.csv(x, stringsAsFactors = FALSE))
        setNames(data, paste0("df", id)) # set data frame names
}

请注意,如果没有参数,您还可以设置工作目录和temp 外部函数。

test &lt;- my_Funk(1:15)为例,调用函数后,可以通过list2env(test, .GlobalEnv)取消列出test

【讨论】:

    猜你喜欢
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 2022-09-23
    • 2020-11-16
    • 2011-05-16
    • 2021-08-05
    相关资源
    最近更新 更多