0

Why raster layer name change to default when using raster::calc function, but not when using Arith-methods:

Toy example copied from Reference manual (calc function).

library(raster)
r <- raster(ncols=36, nrows=18)
r[] <- 1:ncell(r)
names(r) <- "Band1"
r 

rc1 <- calc(r, function(x) { x * 10 })
names(rc1) # Default name "layer"

#But when:
rc2 <- r*10
names(rc2) #It conserves the name "Band1"

I did not find an easy way to check the calc function code?

1

There's no mention of what happens with layer names in the documentation for calc so I suspect the answer is "just because". If you rely on layer names in your code then you should probably explicitly set them any time you think they might change.

Note that arithmetic can change layer names - even though both operands here have the same name, the output is different:

> names(r)
[1] "Foo"
> names(r*r)
[1] "layer"

Even simple functions of one raster can change layer names:

> names(r)
[1] "Foo"
> names(sqrt(r))
[1] "layer"

I think the best advice is to treat layer names as fragile and reset them when you need them, copying them from source rasters at the start of a processing step.

I'm not sure there's always a sensible default when doing arithmetic - suppose you are doing operations on more than one raster, which one do you use? Simpler to let the user decide. The setNames function comes in very handy here:

Two rasters with differing names:

> names(r)
[1] "Foo"
> names(q)
[1] "Bar"

When multiplied, returns neither:

> names(r*q)
[1] "layer"

Wrap in setNames and get a raster:

> rq = setNames(r*q, names(q))
> rq2 = setNames(r*q, names(r))

With whichever names you ask for:

> names(rq)
[1] "Bar"
> names(rq2)
[1] "Foo"
> 

a = setNames(b, n) is essentially the same as a = b; names(a)=n; return(a)

  • Don't you think that this would be a nice option in this function to be filed as an issue on the github site of the raster package? I will do it just in case and wait for his answer. In the meantime I will follow your suggestion. Thank you for your help! – Camilo Erasso Apr 3 at 18:52
  • I think setNames does the job nice enough - see edit. – Spacedman Apr 3 at 19:01
  • It does. I received a quick answer on github.com/rspatial/raster/issues/50. It is so by desig: github.com/rspatial/raster/issues/42 – Camilo Erasso Apr 3 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.