Reputation: 27
I know this is a really easy question, but I am stumped right now.
How do you change 0's or 0.00's to NA's for a SpatialPointsDataFrame in R? I only want to do this for certain columns.
For example, if I have a dataset called l8.stations and I only want to do this for l8.stations[,11:18], how do you do that?
Upvotes: 1
Views: 783
Reputation: 31452
This seems slightly trickier to do than on a standard data.frame. One way to do this is to extract the data columns you want to alter into a standard data.frame. Then change them in the normal way, using data.frame subsetting and assignment - see here.
So for example, changing integer zeros into NA in columns 5:8 we can do this:
df = as.data.frame(l8.stations)[, 5:8] # extract desired columns into a data.frame
df[df == 0] = NA # change values that are zero into NA
l8.stations[1:NROW( l8.stations), 5:8] = df # insert result back into spatial points data frame
Now you also mentioned doing the same thing for values of 0.0. In this case dealing with real number rather than integers, we should really test not for equality to zero, but that the value is smaller than some small number threshold. To understand why we do this with real numbers, rather than simply test they are equal to zero, have a read of this. So, for example to use the cut-off as eps = 1e-10
we can do the same as above but testing for values less than eps
:
df = as.data.frame(l8.stations)[, 5:8]
df[abs(df) < eps] = NA
l8.stations[1:NROW(l8.stations), 5:8] = df
Some reproducible dummy data to test on:
library(sp)
set.seed(1331)
pts = cbind(1:5, 1:5)
dimnames(pts)[[1]] = letters[1:5]
df = data.frame(sample(0:3, 5, T),
sample(0:3, 5, T),
sample(0:3, 5, T),
sample(0:3, 5, T),
sample(0:3, 5, T),
sample(0:3, 5, T),
sample(0:3, 5, T),
sample(0:3, 5, T))
row.names(df) = letters[1:5]
colnames(df) = LETTERS[1:8]
l8.stations = SpatialPointsDataFrame(pts, df)
Upvotes: 1