[R] setting a number of values to NA over a data.frame.

John Kane jrkrideau at yahoo.ca
Wed Feb 7 23:08:52 CET 2007


This is probably a simple problem but I don't see a
solution.

I have a data.frame with a number of columns where I
would like 0 <- NA

thus I have df1[,144:157] <- NA if df1[, 144: 157] ==0
and df1[, 190:198] <- NA if df1[, 190:198] ==0

but I cannot figure out a way do this.  

cata <- c( 1,1,6,1,1,NA)
catb <- c( 1,2,3,4,5,6)
doga <- c(3,5,3,6,4, 0)
dogb <- c(2,4,6,8,10, 12)
rata <- c (NA, 9, 9, 8, 9, 8)
ratb <- c( 1,2,3,4,5,6)
bata <- c( 12, 42,NA, 45, 32, 54)
batb <- c( 13, 15, 17,19,21,23)
id <- c('a', 'b', 'b', 'c', 'a', 'b')
site <- c(1,1,4,4,1,4)
mat1 <-  cbind(cata, catb, doga, dogb, rata, ratb,
bata, batb)

data1 <- data.frame(site, id, mat1)
data1

 # Obviously this works fine for one column

data1$site[data1$site ==1] <- NA  ; data1

but I cannot see how to do this with indices that
would allow me to do more than one column in the
data.frame.

At one point I even tried something like this
a <- c("site")
data1$a[data1$a ==1] <- NA

which seems to produce a corrupt data.frame.

I am sure it is simple but I don't see it.  

Any help would be much appreciated.



More information about the R-help mailing list