[R] How to create an ifelse statement where it matches a different data.frame variable

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Wed Mar 26 18:36:27 CET 2014


Please read and in the future follow the Posting Guide, which requests that you provide a reproducible example... that is, a series of R statements that we can run to get us to your problem point with a small sample data set that resembles yours. Forging on anyway...

The ifelse function applies to vectors, not data frames. That is, as long as both data frames have the same number of rows, you should be able to do things like

CurrentDataFrame$Name <- ifelse( CurrentDataFrame$Name=="NA", PastDataFrame$Name, CurrentDataFrame$Name)

Please note that NA is completely different than "NA" (read the Introduction to R document that comes with R if you need a refresher). If you are really trying to weed out NA values then you would need to do something like

CurrentDataFrame$Name <- ifelse( is.na(CurrentDataFrame$Name), PastDataFrame$Name, CurrentDataFrame$Name)

Also, if you need speed or are pushing the limits of your RAM, the following approach avoids replacing the entire vector:

idx <- is.na(CurrentDataFrame$Name)
CurrentDataFrame[idx,"Name"] <- PastDataFrame[idx,"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 March 26, 2014 9:44:06 AM PDT, Megan Weigel <mw5wags at gmail.com> wrote:
>Hello,
>
>Hopefully there is an answer for this, but I need an ifelse statement
>that
>replaces and returns a value based on a different dataframe. For
>example:
>
>CurrentDataFrame<-ifelse(CurrentDataFrame$Name=="NA",match(CurrentDataFrame$Code
>with PastDataFrame$Code),replace(CurrentDataFrame$Name) with
>(PastDataFrame$Name)
>
>
>I hope that makes sense.
>
>Thank you very much,
>
>Johnson
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>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.




More information about the R-help mailing list