mardi 26 octobre 2021

Problems with raster analysis (slope and for cycle)

I have a problem running a cycle on a raster.

Background: I have a treefile, a Large SpatialPointDataFrame. Within this treefile I have data about trees like height, dbh (diameter at breast height), species and slope. The slope is extracted from a DEM in this way (r.temp is a copy of the DEM):

r.temp = raster::terrain(r.temp, opt="slope", unit="degrees") # calculate slope
treefile@data$slope = round(raster::extract(r.temp, treefile)) # assign slope to trees

The focus of my script is to run a model (in an R package) about tree stability and put the output on a raster of the same size as the DEM. To do so I'm dividing the raster into tiles, for each tile I need to change the species name according to the slope. So I did this cycle:

for( i in 1:nrow(treefile@data)){
  
  if( treefile@data[i,"species"] == "NS"){
    # check slope and assign correct species code
    if( treefile@data[i,"slope"] <= 20 ){
      treefile@data[i,"species"] = "U_NS_f"
    } else {
      treefile@data[i,"species"] = "U_NS_s"
    }
  }

Here comes the problem: R says that I have a missing value in this cycle. I think it is because in some tiles I have very little data so I was not able to calculate the slope, so when I call treefile@data$slope it gets confused. Considering this idea I added another cycle to solve this issue. The idea is that if I don't have any slope value there's shouldn't be output. The script now looks like this:

if( nrow(treefile@data)==0 ){
 out1 = r.crop
 out1[out1] = NA
 out1 = stack(out1,out1,out1)
return(out1)

} else {

# assign correct species parameters according to slope 
for( i in 1:nrow(treefile@data)){
 if( treefile@data[i,"species"] == "NS"){
    # check slope and assign correct species code
    if( treefile@data[i,"slope"] <= 20 ){
      treefile@data[i,"species"] = "U_NS_f"
    } else {
      treefile@data[i,"species"] = "U_NS_s"
    }
  }
}

When I run the script R shows me again the same problem as before... But I cannot understand where the error lies...

Aucun commentaire:

Enregistrer un commentaire