Back to main page.

Example: Identifying Points in Regions

The task

In this example, we identify which of eight regions each point in a scatter plot belongs to.

R functions

getRegion.R

C++ function

getRegion.cpp

library(Rcpp)
## Warning: package 'Rcpp' was built under R version 3.4.2
sourceCpp('getRegion.cpp')
## 
## > set.seed(10)
## 
## > table(getRegionCPP(x = rnorm(100), y = rnorm(100, 
## +     0.1)))
## 
##  1  2  3  4  5  6  7  8 
## 15 25 17 17  5  7  7  7
source('getRegion.R')
n = 1e3; x = rnorm(n,0,.5); y = rnorm(n,.1,1)
Regions = data.frame(
  x = x, y=y,
  R_loop = getRegion_loop(x,y),
  R_vec  = getRegion_vec(x,y),
  R_all  = getRegion_all(x,y),
  CPP    = getRegionCPP(x,y)
)
## Test that there are no discrepencies
with(Regions,!{any(R_loop!=R_vec) | any(R_vec!=R_all) | any(R_vec!=CPP)})
## [1] TRUE
Regions %>% mutate(Region=factor(CPP)) %>% ggplot(aes(x=x,y=y,color=Region)) +
  geom_point() + theme_minimal()

library(microbenchmark)
print(microbenchmark(getRegion_loop(x,y),getRegion_vec(x,y),getRegion_all(x,y),
                     getRegionCPP(x,y)),digits=2)
## Unit: microseconds
##                  expr    min   lq mean median   uq  max neval
##  getRegion_loop(x, y) 1874.4 1987 2344   2107 2529 4517   100
##   getRegion_vec(x, y) 2883.4 3061 3504   3208 3621 8815   100
##   getRegion_all(x, y)  153.7  171  205    177  227  525   100
##    getRegionCPP(x, y)    5.9   19   22     23   25   56   100

Exercise

  1. Write an R function to identify coordinates in the regions between the lines \(y=-\frac{1}{2}x\) and \(y=2x\) as labeled below:

  1. Write a C++ function for the same task.

  2. Compare the computation times of your implementation using microbenchmark. How is this example different than the previous one?

Back to main page.