[R] Replace selected columns of a dataframe with NA

Chris Beeley chris.beeley at gmail.com
Mon Jun 20 10:40:35 CEST 2011


I am using the following command to replace all the missing values and
assorted typos in a dataframe with NA:

mydata[mydata>80]=NA

The problem is that the first column contains values which should be
more than 80, so really I want to do it just for
mydata[,2:length(mydata)]

I can't seem to re-write the code to fit:

mydata[,2:length(mydata)>80]=NA # no error message, but doesn't work-
doesn't do anything, it would seem

I realise I can just keep the first column somewhere safe and copy it
back again when I'm done, but I wondered if there was a more elegant
solution, which would be much more important, if say I just wanted to
replace the odd columns, or something like that.

I found this code on the internet too:

idx <- which(foo>80, arr.ind=TRUE)
foo[idx[1], idx[2]] <- NA

But I can't seem to rewrite that either, for the same reason

Many thanks!

Chris Beeley
Institute of Mental Health



More information about the R-help mailing list