coalesce with wrapr

November 3, 2018
By

(This article was first published on R – Win-Vector Blog, and kindly contributed to R-bloggers)

coalesce is a classic useful SQL operator that picks the first non-NULL value in a sequence of values.

We thought we would share a nice version of it for picking non-NA R with convenient operator infix notation wrapr::coalesce(). Here is a short example of it in action:

library("wrapr")

NA %?% 0

# [1] 0

A more substantial application is the following.

library("wrapr")

d <- wrapr::build_frame(
  "more_precise_sensor", "cheaper_back_up_sensor" |
  0.31                 , 0.25                     |
  0.41                 , 0.5                      |
  NA_real_             , 0.5                      )

print(d)

#   more_precise_sensor cheaper_back_up_sensor
# 1                0.31                   0.25
# 2                0.41                   0.50
# 3                  NA                   0.50

d$measurement <- 
   d$more_precise_sensor %?% d$cheaper_back_up_sensor

print(d)

#   more_precise_sensor cheaper_back_up_sensor measurement
# 1                0.31                   0.25        0.31
# 2                0.41                   0.50        0.41
# 3                  NA                   0.50        0.50

To leave a comment for the author, please follow the link and comment on their blog: R – Win-Vector Blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)