Calling Loops dataframes in R

Asked

Viewed 112 times

2

I have a series of data frames, which I will work on several times in some loops.

The problem I find is that I cannot "call them" correctly to perform other actions, comparisons, etc.

My code:

list <- c("2","3","4","5","6","7","8")
for (x in list){
  name = as.data.frame(paste("europe_",x))
  species_Europe_WGS84 <- st_as_sf(name,coords= c("lon","lat"), crs=4326)#WGS84 (EPSG: 4326) 
  st_write(species_Europe_WGS84,paste("species_Europe", x, "_WGS84.shp", sep = ""), driver= "ESRI shapefile")
}

From what I can see the Paste command does not work for calling objects.

Trying a minimally replicable example:

nome <- rep(LETTERS[1:10],10)
lat <- rnorm(100, mean = 30, sd =5)
long <- rnorm(100, mean = 80, sd =5)
sep <- rep(paste0("nome",1:5), 20)

df <- as.data.frame(cbind(nome, lat, long, sep))
list2env(split(df, df$sep), envir = .GlobalEnv)

list <-c(1,2,3,4,5)

for (i in list){
  ### chamar dataframe
  write.csv(paste0("nome",i),paste0("nome_",i,".csv"))
}

The option to use the loop is that there will be more actions within the code, not just in save.

1 answer

3


The function get does exactly what is necessary: she understands that you are looking for an object present in Workspace called nome_i, with this index i varying. See an example of how to use it below.

nome <- rep(LETTERS[1:10],10)
lat <- rnorm(100, mean = 30, sd =5)
long <- rnorm(100, mean = 80, sd =5)
sep <- rep(paste0("nome",1:5), 20)

df <- as.data.frame(cbind(nome, lat, long, sep))
list2env(split(df, df$sep), envir = .GlobalEnv)

lista <- c(1,2,3,4,5)

for (i in lista){

  ### chamar dataframe

  write.csv(x = get(paste0("nome", i)), 
            file = paste0("nome_",i,".csv"),
            row.names = FALSE,
            quote = FALSE)
}

I made the argument row.names = FALSE and quote = FALSE in function write.csv so that the lines are not numbered and so that no quotes appear in the final file.

A final remark: I didn’t use the name list to save the numbers of your files, as this is the name of a native command of R. So I preferred to use lista in his stead.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.