4 ms·
Everything being a vector is one of the best things about R. You can write a function that looks sensible for scalars: in_circle <- function(x, y) { x^2
by nequo 4y ago
Everything being a vector is one of the best things about R. You can write a function that looks sensible for scalars:
in_circle <- function(x, y) {
x^2 + y^2 <= 1
}
It works as you would expect:
> in_circle(.2, .3)
[1] TRUE
> in_circle(1, 1)
[1] FALSE
But you can also evaluate `in_circle` for multiple points with a single function call. You can pass in vectors as arguments, and you'll get back the results as a vector:
> in_circle(c(.2, 1), c(.3, 1))
[1] TRUE FALSE
Since the columns of a data frame, a tibble, or a data table are all vectors, it becomes very natural to apply simple functions to them. With tibbles:
> data <- tibble(a = c(.2, 1), b = c(.3, 1))
> data
# A tibble: 2 × 2
a b
<dbl> <dbl>
1 0.2 0.3
2 1 1
> data %>% mutate(inside = in_circle(a, b))
# A tibble: 2 × 3
a b inside
<dbl> <dbl> <lgl>
1 0.2 0.3 TRUE
2 1 1 FALSE