0

I have two dataframes below. The first image is called "hp_cons_x" and the second image is called "aux". I need to create a loop that saves multiple files in the following order:

dir(.../rgn11cd/lad21cd/msoa11cd.rdata), where rgn11cd and lad21cd are folders that needs to be created.

With that in mind, I did the following code:


aux = hp_cons_x %>%
  select(rgn11cd, lad21cd, msoa11cd) %>%
  distinct() %>%
  drop_na()


for(i in 1:nrow(aux)){
 
  dir.create(paste0("01 Raw Data/EPC/processed_buckets/test/", aux[i]$rgn11cd,aux[i]$lad21cd))
  
  save(hp_cons_x, file = paste0("01 Raw Data/EPC/processed_buckets/test/",aux[i]$rgn11cd, aux[i]$lad21cd, aux[i]$msoa11cd, ".rdata"))
  
}

Unfortunately, i got the following error message:

Error in dir.create(paste0("01 Raw Data/EPC/processed_buckets/test/",  : 
  invalid 'path' argument

What should I do in order to fix this?

hp_cons_x

aux

  • 1
    Try `dir.create(paste0("01 Raw Data/EPC/processed_buckets/test/", aux[i]$rgn11cd,aux[i]$lad21cd), recursive = TRUE)` – Ric Feb 09 '23 at 23:12
  • Hello, I did this just know and the same error appears – Fredie Didier Feb 10 '23 at 00:23
  • 2
    what are you trying to get with ```aux[i]$rgn11cd```? Should not be ```aux$rgn11cd[i]``` instead? ```dir.create(paste0("01 Raw Data/EPC/processed_buckets/test/", aux$rgn11cd[i],aux$lad21cd[i]))``` – asaei Feb 10 '23 at 03:13
  • Welcome to Stack Overflow! Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Feb 10 '23 at 06:23
  • 1
    Let's show a concrete example: if we do `mtcars[2]` (as in your `aux[i]`), we get the entire second column )as a 1-column frame). If we add the `$` reference there `mtcars[2]$cyl` then we get a vector as long as the number of rows, but only because the second column happens to be named `cyl`; if we instead do `mtcars[2]$mpg`, we get `NULL` because the single-column frame returned by `mtcars[2]` does not contain the column `mpg`. We're sunk at that point, since `dir.create` only accepts `path=` of length 1. I suggest you take @asaei`s recommendation to swap `[i]` and `$` in your references. – r2evans Feb 10 '23 at 14:43

0 Answers0