[R] Replace NAs in one column with data from another column

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Wed Sep 8 20:22:51 CEST 2010


one way is the following:

m <- data.frame(x = rnorm(100), y = rnorm(100), z = rnorm(100))
m$z[sample(100, 20)] <- NA

m$z.new <- ifelse(is.na(m$z), m$x, m$z)


I hope it helps.

Best,
Dimitris


On 9/8/2010 8:17 PM, Jakob Hedegaard wrote:
> Hi list,
>
> I have a data frame (m) with 169221 rows and 10 columns and would like to make a new column containing the content of column 3 but replace the NAs in column 3 with the data in column 1 (from the same row as the NA in column 3). Column 1 has data in all rows.
>
> My first attempt was:
>
> for (i in 1:169221){
> if (is.na(m[i,3])==TRUE){
> m[i,11]<- as.character(m[i,1])}
> else{
> m[i,11]<- as.character(m[i,3])}
> }
>
> Works - but takes too long time.
> I would appreciate alternative solutions.
>
> Best regards, Jakob
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014



More information about the R-help mailing list