0

I want to make a function that reads all csv of a local directory and save them as a list of dataframes in my R environment. I tried the follwing:

 getdflist <- function(directory = getwd()) {
      setwd(directory)
      monitors <- list.files(directory)
      dataframes <- vector("list", length(monitors))
      for (i in seq_along(monitors)) {
        dataframes[[i]] <- read.csv(monitors[[i]])
        print(i)
      }
      dataframes
}

but it only prints i and doesn't save the list in my environment

Could anyone help me to see the error on my code?

Note: When I try to run it as a code (not a function):

> monitors <-list.files(getwd())
> dataframes <- vector("list", length(monitors))
> for (i in 1:length(monitors)){
+     dataframes[[i]] <- read.csv(monitors[[i]], sep = ",")
+ }
>

it works and saves it as a dataframes list with 65.5MB weight, the problem is when I pass it as a function. May be it could be because the lexical scoping?

Solution for this question is the most valued answer for this: How to make object created within function usable outside

Rui Barradas
  • 57,195
  • 8
  • 29
  • 57
Mauro
  • 373
  • 1
  • 7
  • 19
  • Your function returns nothing. After the `for` loop write `dataframes` as the last instruction of the function. Also, instead of `dataframes – Rui Barradas Nov 26 '17 at 15:58
  • Why it doesn't return nothing if I have already created the dataframes object? I mean, It would overwrite each element of dataframes with the resulting dataframe of apply read.csv function, wouldn't it? – Mauro Nov 26 '17 at 16:13
  • It doesn't return the `dataframes` object because you are forgetting my first suggestion in the comment above: ***the last instruction of a function is its return value.*** So you need to write just `dataframes` as the last line of the function. I will now edit your code – Rui Barradas Nov 26 '17 at 17:50
  • Rui Brradas thanks for help, but my problem was other, the solution is in a link to other question in my new edition of this quiestion, sorry for not was able to explain myself. – Mauro Nov 26 '17 at 18:03

1 Answers1

3
setwd("directory")
dfs = list.files(pattern = "*.csv")
getdflist <- lapply(dfs, read.csv)
names(getdflist) <- dfs
Keshav M
  • 1,259
  • 10
  • 22