Search code examples
rtidyversegeo

for loop with mutate only outputs last result


I'm sorry if it's a duplicate, and for the lack of reproducibility, I'd have to link you the files.

What I'm trying to do is this:

I have a data frame with coordinates and names, let's say

df <- tribble(
  ~Species, ~lat, ~lon,
  "a",42.92991, 11.875801,
  "b",42.92991, 11.875801,
  "c",43.91278, 3.513611,   
  "d",43.60851, 3.871755,   
  "e",39.24373, 9.120478
)

I also have a folder with tifrasters, such as

files <- list.files(path="~/world/", pattern="*.tif$", full.name=TRUE, all.files=TRUE)

Now for each iteration I'd like to:

  • create a new column on the data frame with the file name
  • insert in that column the extracted value for the corresponding lat and lon

I've tried using this for loop, and while on paper looks just fine, I don't understand why it outputs to funvar the last result only. I't like it overwrites the result instead of appending it.

If I use a similar loop with mutate and simpler objects, it appends them, so I'm not sure what the problem could be

for(i in files){  
fraster<- raster(i)

fname<-gsub(".*//|[.].*", "", i)

funvar<-dplyr::mutate(fundata, !!fname:= raster::extract(fraster, coordinates(data.frame(lat,lon))))
}

Thanks!


Solution

  • The way I solved it is a bit of an hack, but works. I explicitly assign the new column to a data frame, like this. I'm still notsure why mutate doesn't do that by itself

    for(i in files){  
    fraster<- raster(i)
    
    fname<-gsub(".*//|[.].*", "", i)
    
    funvar<-dplyr::mutate(fundata, !!fname:= raster::extract(fraster, coordinates(data.frame(lat,lon))))
    
    fundata[fname] <- funvar[[fname]]
    }