[R-sig-Geo] Antw: arithmetic with layers from a raster stack/brick

Oscar Perpiñán Lamigueiro oscar.perpinan at gmail.com
Fri Mar 1 10:17:24 CET 2013


Hi,

Another solution:

r <- raster(nrows=2, ncols=2)
r[] <- 1:ncell(r)
s <- stack(r, r, r, r)
names(s) <- letters[1:4]

## all the layers
sum(s)
## only a subset
sum(subset(s, c('a', 'b')))

Best,

Oscar.

Etienne B. Racine <etiennebr at gmail.com> writes:

> I wouldn't recommend using this for general purpose, but this should work:
>
> for (i in 1:nlayers(s)) {
>   assign(names(s)[i], s[[i]])
> }
>
> Etienne
>
>
> 2013/2/28 Matteo Mattiuzzi <matteo.mattiuzzi at boku.ac.at>
>
>> Dear Ani,
>>
>>
>> Your "a" and "b" are not objects, they are the name the layers in your
>> object "s". So you can't treat it that way.
>>
>>
>> Maybe this is what you want?
>>
>>
>> require(raster)
>> r<- raster(nrows=2, ncols=2)
>> r[]<-1:ncell(r)
>> s<-stack(r,r)
>> names(s)<-c("a","b")
>>
>>
>>
>> r1<- s[["a"]] + s[["b"]]
>>
>>
>> Matteo
>>
>> >>> aniruddha ghosh  28.02.13 21.26 Uhr >>>
>> Dear List,
>>
>> I'm trying to perform some arithmetic operation with layers of a raster
>> object. What I'm trying is
>>
>> >require(raster)
>> >r<- raster(nrows=2, ncols=2)
>> >r[]<-1:ncell(r)
>> >s<-stack(r,r)
>> >names(s)<-c("a","b")
>>
>> # now I want to add the layers of the raster "r" using their corresponding
>> names,i.e. "a" and "b" so that I get
>>
>> >r1<-a+b
>>
>> I don't want to use subset (or any other methods) to define "a" or "b".
>> This may be very trivial, but I couldn't do it.
>>
>> Any suggestions?
>>
>> Thanks
>> --
>> Ani
>>
>>     [[alternative HTML version deleted]]
>>
>> _______________________________________________
>> R-sig-Geo mailing list
>> R-sig-Geo at r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>>
>> _______________________________________________
>> R-sig-Geo mailing list
>> R-sig-Geo at r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>>
>
> 	[[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo

-- 
Oscar Perpiñán Lamigueiro
Grupo de Sistemas Fotovoltaicos (IES-UPM)
Dpto. Ingeniería Eléctrica (EUITI-UPM)
URL: http://procomun.wordpress.com
Twitter: @oscarperpinan



More information about the R-sig-Geo mailing list