Question

I think I am missing something simple, but I am having trouble accessing elements of a list, in a lapply.

Problem: I have a number of files on a FTP I want to download and read. So I need to specify the location, download them and read them. All which I thought can be handled best with a few lists, but I can't really get it to work in my function.

I would like to be able to start with calling a lapply(lst,...) because I need both the variable name (a) and the url in the same function, to download & name them easily.

Code-example:

a <- "ftp://user:pass@url_A1" 
b <- "ftp://user:pass@url_B1" 
c <- "ftp://user:pass@url_C1" 
d <- "ftp://user:pass@url_D1"

lst <- list(a, b, c, d)
names(lst) <- c("a", "b", "c", "d")

Desired goal:

print(lst[[1]]), ...., print(lst[[4]])

What I've tried:

lapply(lst, 
function(x) print(x[[]]) 
)

# Error!

My real code looks something more like:

lapply(lst, 
       function(x) download.file(url = x[[]], # Error!  
                               destfile = paste0(lok, paste0(names(x), ".csv")),
                               quiet = FALSE)
      )

EDIT:

I know the x[[]] throws an error, it is just to illustrate what I would like to get.

Was it helpful?

Solution

Untested:

lapply(names(lst),function(x){
download.file(url = lst[[x]],
destfile = paste0(lok,paste0(x,".csv")),
quiet = FALSE)
}

This should work given lok is defined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top