0

Lets say there are these documents I want to fetch I named in a very clear pattern for example EIS_Chip14_1_pre. Everything is constant except the two numbers in the name which range from 6:18 and 1:4. Im using a for loop:

How do I include both "i" and "n" into my title of the storage vector so I dont overwrite it?

dat <- vector(mode = "list")
i <- numeric(13)
n <- numeric(4)
for(i in 6:18){
  for(n in 1:4){
    path <- paste0("C:/.../downloads/EIS_Chip",i,"_", n, "_pre.dat")
    dat_(i)[[n]] <- read.csv(file = path)
  }
}
  • Related: https://stackoverflow.com/questions/5413188/reading-csv-files-in-a-for-loop-and-assigning-dataframe-names – MrFlick Jun 13 '18 at 18:10
  • Related: https://stackoverflow.com/questions/29685768/using-variable-in-read-csv-command-in-r – MrFlick Jun 13 '18 at 18:10
  • Those seem like more complicated questions related to the same idea, I'm trying to use those to solve my problem, but I'm relatively new to R so its not easy. – Zachary Donnini Jun 13 '18 at 18:16
  • Well, maybe try implementing one of those solutions and describe where exactly you are getting stuck. Start with building a file path with the `paste()` function. – MrFlick Jun 13 '18 at 18:17
  • Now my major problem is how to get both I and N into the storage vector name so I don't overwrite it – Zachary Donnini Jun 13 '18 at 18:31

1 Answers1

0

This isn't necessarily the best solution, but it should do the trick for you.

At the top of your outer loop, initialize a variable, tmp here, with an empty list. Inside your inner loop, store the results into elements of that list using [[. When your inner loop is finished, assign the value in tmp to a variable dynamically named using paste0.

dat <- vector(mode = "list")
i <- numeric(13)
n <- numeric(4)
for(i in 6:18){
  tmp = list()
  for(n in 1:4){
    path <- paste0("C:/.../downloads/EIS_Chip",i,"_", n, "_pre.dat")
    list[[n]] <- read.csv(file = path)
  }
  assign(paste0("dat_",i),tmp)
}

A better way to approach this though could be to use expand.grid to get every combination of i and n, then write a function that reads in a file using those values. Finally, using something like purrr::pmap to iterate over your values. This will return a list with 52 elements, one for each file you loaded.

read_in_file = function(i,n){
  path = paste0("C:/.../downloads/EIS_Chip",i,"_", n, "_pre.dat")
  return(read.csv(file=path))
}

combinations = expand.grid(i = 6:18, n = 1:4)
dat = purrr::pmap(combinations,read_in_file)

This works because expand.grid returns a data.frame which is a special kind of list. Because we named the inputs appropriately, purrr::pmap processes the list of inputs and assigns them correctly to the function.

Mark
  • 4,387
  • 2
  • 28
  • 48