Trying to download data in a for loop and writing it to csv

Hi,
I try to download data from BfS Switzerland with the following package -> install.packages("BFS")

I works when I put this code in the R concole:

data <- bfs_get_data(number_bfs = "px-x-1502010000_101", language = "de")
d <- as.data.frame(data, column.name.type = "text", variable.value.type = "text")
write_csv(d, "C:\filepath\table_px-x-1502010000_101.csv")

But when I try to create a list of the "number_bfs" numbers and then loop over it and write it to csv path, it creates this error (german):

Fehler in basename(path) :
Problem bei der Konvertierung des Dateinamens -- zu lang?
Zusätzlich: Warnmeldung:
In if (is_url(path)) { :
Bedingung hat Länge > 1 und nur das erste Element wird benutzt

Here to code I try to run:

list1 <- list("px-x-1502020100_104")

*# loop *
for (p in list1) {

  • data <- bfs_get_data(number_bfs = p, language = "de")*
  • d <- as.data.frame(data, column.name.type = "text", variable.value.type = "text")*
  • path <- file.path("C:/filepath",d) *
  • write_csv(d, file.path(path,".csv"))*

}

I want to append the file path with the list items...

It downloads the data but gives then the above error...

Any help?

I think path sould be built from p and not from d.

for (p in list1) {
  
  data <- bfs_get_data(number_bfs = p, language = "de")
  d <- as.data.frame(data, column.name.type = "text", variable.value.type = "text")*
  path <- file.path("C:/filepath",p) 
  path <- paste0(path,".csv")
  write_csv(d, path)
        
}

Thanks @FJCC !
It worked.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.