1

How can I create a function in R that takes a vector as an argument and uploads multiple csv files with the range defined by the vector?

I did something like this:

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
}

When I upload the function into the global environment and then call it with my_Funk(1:5) - Nothing happens. I also don't see any temp variables or any csv files

If I execute the part of my function one by one it works perfectly fine But, it doesn't work as a whole

Gilbert
  • 3,570
  • 18
  • 28
  • Any variables created inside the function but not returned from the function disappear after the function is done running. Your function should return a list with the data.frames you wish to load and you can save that list for latter. Avoid [using assign()](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad). – MrFlick Mar 28 '18 at 15:11

1 Answers1

0

You can store your data in a list of data frames. Here is an example.

# 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
}

Note that you can also set your working directory and temp outside function if there are not arguments.

After calling the function with test <- my_Funk(1:15) for example, you can unlist testby using list2env(test, .GlobalEnv).

nghauran
  • 6,648
  • 2
  • 20
  • 29