Hi everyone, I'm creating a new topic since I couldn't find answers to my question in past publications.
The problem:
One of the variables of my data frame contains urls (one per observation). Each of these url goes directly to an image. I would like to create a loop that allows me to access each of these urls and save the images in a specific folder.
I hope someone can give me some advice to realize that task.
Welcome to the community! It is always much easier to help when you have some code or a minimally reproducible example of your code. I am going to write some dummy code that should get you there.
library(jpeg) #to read and write the images
library(here) #to save the files to the right location - this only works if you're working with a R project
#Code to read one file and save it will look something like this:
myurl <- "http://upload.wikimedia.org/wikipedia/commons/9/95/Apollonian_spheres.jpg"
#Creating temporary place ot save
z <- tempfile()
#Downloding the file
download.file(myurl,z,mode="wb")
#Reading the file from the temp object
pic <- readJPEG(z)
#Saving to your location
writeJPEG(pic,"image.jpg")
# cleanup
file.remove(z)
Looped example:
#Looped code
for (i in 1:100) { #change 100 with your number of rows to read through
myurl <- paste(df[i,1], sep = "") #you need the exact column number so change 1 to that value and change df to your dataframe's name
z <- tempfile() #same as above
download.file(myurl,z,mode="wb")
pic <- readJPEG(z)
writeJPEG(pic, paste("image", "i", ".jpg", sep = "")
#alternatively you can do writeJPEG(pic, here("desired folder", paste("image", "i", ".jpg", sep = ""))
#you can do setwd to the folder you want to write the files but here is much better
file.remove(z)
}