[R] Replace NaN with value from the same row

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Sun Oct 18 20:06:44 CEST 2015


Next time send your email using plain text format rather than HTML so we see what you saw.

Try 

idx <- is.na( df$mean )
df[ idx, "mean" ] <- df[ idx, "offset" ]

BTW there is a commonly-used function called df, so you might improve clarity by using DF for your temporary data frame name.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On October 18, 2015 10:48:14 AM PDT, Jonathan Reardon <jonathanreardon at outlook.com> wrote:
>Hi everyone,
>A simple question, but i cannot figure this out.
>
>I have a data-frame with 4 columns (onset, offset, outcome, mean):
>onset offset outcome   mean8   72071  72503       1  7244615 142598
>143030       1    NaN30 293729 294161       1 294080
>For each 'NaN' in the mean column, i want to replace that NaN with the
>'offset' value in the same row.
>Intended outcome: 
>onset offset outcome   mean8   72071  72503       1  7244615 142598
>143030       1    14303030 293729 294161       1 294080
>I have tried:
> df$mean <- replace(df$mean, is.na(df$mean), df$offset)
>but i get the error message: 'number of items to replace is not a
>multiple of replacement length'. I'm assuming because this is trying to
>insert the whole 'offset' column into my one NaN cell. Is this a
>correct interpretation of the error message?
>Can anyone tell me how to replace any mean row NaN's  with the offset
>value from that very same row?
>I don't want to use any pasting etc as this needs to be used as part of
>a function working over a large dataset than the one shown here.
>Cheers
>Jonathan 		 	   		  
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>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.



More information about the R-help mailing list