So I've created a file that reads into a data frame in the same way as yours:
> str(v2)
'data.frame': 360 obs. of 720 variables:
BUT data.frame isn't really the right thing here. Its really meant for record-oriented data, where each row is a record and each column is a potentially different variable for that record (eg each row is a person, the columns are name, age, height, etc).
So you really only need to scan
the data in as one long vector and feed it to a raster.
Step 1, define an empty raster of the right size and shape (note I'm assuming the raster covers the whole world, so the limits are not the cell centres):
> m2=raster(nrow=360,ncol=720,xmn=-180,xmx=180,ymn=-90,ymx=90)
Step 2, read numeric values into the raster data slot:
> m2[]=scan("d.txt",what=1)
Read 259200 items
And give it a projection if needed:
> projection(m2)="+init=epsg:4326"
> plot(m2)
If you want to check that the resolution and the cell centres are as expected, use these functions:
> res(m2)
[1] 0.5 0.5
> xFromCol(m2,1:10)
[1] -179.75 -179.25 -178.75 -178.25 -177.75 -177.25 -176.75 -176.25 -175.75
[10] -175.25
> yFromRow(m2,1:10)
[1] 89.75 89.25 88.75 88.25 87.75 87.25 86.75 86.25 85.75 85.25
which shows the resolution is half a degree and the cell centres (or at least the first 10) are at those specified coordinates.
Perhaps you need to first look at how ifelse
works. I get the same results when I use it "stand-alone" and within a call to raster::overlay
.
a <- rep(2, 5)
b <- rep(1, 5)
d <- c(2, NA, 2, NA, 2)
library(raster)
r <- raster(nrow=1, ncol=5)
A <- setValues(r, a)
B <- setValues(r, b)
D <- setValues(r, d)
s <- stack(A,B,D)
ifelse(a==2 & b==1 & d==2, 1, 0)
#[1] 1 NA 1 NA 1
res <- overlay(s, fun = function(x,y,z) ifelse( x == 2 & y == 1 & z ==2, 1, 0) )
values(res)
#[1] 1 NA 1 NA 1
ifelse(a==1 & b==1 & d==2, 1, 0)
#[1] 0 0 0 0 0
res <- overlay(s, fun = function(x,y,z) ifelse( x == 1 & y == 1 & z ==2, 1, 0) )
values(res)
#[1] 0 0 0 0 0
This is why that happens:
FALSE & NA
#[1] FALSE
TRUE & NA
#[1] NA
So if you want NA
values to trump FALSE
you need to write another function. You can also do some post-processing after overlay
:
msk <- calc(s, fun=function(x) any(is.na(x)))
resm <- mask(res, msk, maskvalue=TRUE)
Best Answer
To put this into a vectorized function you can use ifelse. If you stack your rasters then you do not need to piecemeal the reclassification and can apply a function to the stack.
Prepare data
Write reclassification function
Apply function to raster stack