[R] Re: [R] Re: [R] replace NA´s
John Fox
jfox at mcmaster.ca
Mon Jan 13 22:21:02 CET 2003
Dear Jason and Juan,
At 09:11 AM 1/14/2003 +1300, Jason Turner wrote:
>On Mon, Jan 13, 2003 at 05:15:02PM +0000, juan pablo perez wrote:
> > what should I do to replace in a data frame NA´s with zeroes?
>
>I use lapply
>
> > dd <- data.frame(a=c(1,2,NA,4),b=c(NA,2,3,4))
> > dd
> a b
>1 1 NA
>2 2 2
>3 NA 3
>4 4 4
> > dd2 <- data.frame(lapply(dd,function(x,...){x[is.na(x)] <- 3.14159 ; x}))
> > dd2
> a b
>1 1.00000 3.14159
>2 2.00000 2.00000
>3 3.14159 3.00000
>4 4.00000 4.00000
>
>That will generate a warning message for each non-numeric column in
>your data frame. A tidier way is left as an exercise. ;)
Here's a pretty simple expression using a for loop over columns (and
testing for numeric data):
for(i in 1:ncol(dd)) if(is.numeric(dd[,i])) dd[is.na(dd[,i]), i] <- 0
I hope that this helps,
John
____________________________
John Fox
Department of Sociology
McMaster University
email: jfox at mcmaster.ca
web: http://www.socsci.mcmaster.ca/jfox
More information about the R-help
mailing list