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
  • 70,273
  • 8
  • 34
  • 66
Mauro
  • 477
  • 1
  • 9
  • 22
  • Your function returns nothing. After the `for` loop write `dataframes` as the last instruction of the function. Also, instead of `dataframes <- list(...)` before the loop, it would be much better `dataframes <- vector("list", length = length(monitors))`. – 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,309
  • 1
  • 13
  • 24
  • It's a good Idea to use lapply, but it keeps not saving the list in my R environment. – Mauro Nov 26 '17 at 15:44
  • 1
    Two notes: 1) you don't need to create `getdflist <- list()`, `lapply` will do it for you; 2) instead of `read.table` use `read.csv`, it's the **same** function with some arguments set, such as `sep = ",", header = TRUE`. Anyway, upvote – Rui Barradas Nov 26 '17 at 15:56
  • @RuiBarradas has it may be to do with lexical scoping? Because I don't understand why it works if I run it as a code but not as a function. – Mauro Nov 26 '17 at 16:35