1

I am calculating the percentage of the impact within multiple rasters. I have one raster with a sum of whole variables (SUM). Then I have 9 rasters that I want to loop and calculate the percentage of the impact (Variables). I am using the function because I will use different inputs. When the function stops I want to have a text file or whatever is possible to export. I tried using rbind() but it does not work it is always empty when the function is executed. Here is the code:

Var_Sum_Impact(EU_HS_45_2041_SUM.r[[1]], EU_HS_45_2041_Var_Medi_Steppic.r)

results = data.frame(col1=numeric(), stringsAsFactors=FALSE)

Var_Sum_Impact = function(SUM, Variables) {
  for (i in 1:9){
    Var = cellStats(Variables[[i]], stat='mean')
    Su = cellStats(SUM, stat='mean')
    Perc = Var/(Su/100)
    print(Perc)
    results = rbind(results, Perc)
    }
}

And here is the result I get from that print but "results" is empty (0 obs.). The calculation is correct:

[1] 9.418741
[1] 20.39071
[1] 12.96036
[1] 5.910591
[1] 4.998413
[1] 21.37485
[1] 6.379199
[1] 4.383655
[1] 14.18348
2
  • try results$col1[i] <- Perc Commented Sep 7, 2018 at 8:17
  • Thank you Vincent. I have added also return in the function I have got this (what seems correct but the results are still empty when I write View(results)): col1 1 9.418741 2 20.390715 3 12.960364 4 5.910591 5 4.998413 6 21.374847 7 6.379199 8 4.383655 9 14.183477 Commented Sep 7, 2018 at 8:42

1 Answer 1

1

rbind isn't working as you expect here because you are trying to bind a data frame to a vector. So you need to either make Perc a data frame (or make results a vector and join each iteration using c()). You also need to return results after your for loop.

I also think instantiating results should happen inside your function

I think this should work (but haven't run it):

Var_Sum_Impact = function(SUM, Variables) {
  results = data.frame(col1=numeric(), stringsAsFactors=FALSE)
  for (i in 1:9){
    Var = cellStats(Variables[[i]], stat='mean')
    Su = cellStats(SUM, stat='mean')
    Perc = data.frame(col1 = Var/(Su/100), stringsAsFactors = FALSE)
    print(Perc)
    results = rbind(results, Perc)
    }
    results # return results
}
## call this after your function, right?
Var_Sum_Impact(EU_HS_45_2041_SUM.r[[1]], EU_HS_45_2041_Var_Medi_Steppic.r)

I'd also look into using lapply over the Variables object:

results_l <- lapply(Variables, function(V) {
        Var = cellStats(V, stat='mean')
        Su = cellStats(SUM, stat='mean')
        data.frame(col1 = Var/(Su/100), stringsAsFactors = FALSE)
}) ## produces a list of data frames you can rbind together
results <- do.call(rbind, results_l)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.