Skip to content

Instantly share code, notes, and snippets.

View sharlagelfand's full-sized avatar
💅
#rstats

Sharla Gelfand sharlagelfand

💅
#rstats
View GitHub Profile
library(tidyr)
df <- tribble(
~Date, ~Fruit, ~Sold,
"2020-02-01", "Apple", 5,
"2020-02-01", "Banana", 1,
"2020-02-02", "Apple", 2
)
df_complete <- df %>%
library(testthat)
library(dplyr, warn.conflicts = FALSE)
# expect_equal() returns silently if they're the same
expect_equal(iris, iris)
# but with an error if they're not
expect_equal(iris, mtcars)
#> Error: `iris` not equal to `mtcars`.
#> Names: 5 string mismatches
divide_by_two <- function(x, call. = FALSE) {
if(!is.numeric(x)) {
stop("IT'S NOT NUMERIC", call. = call.)
} else {
x/2
}
}
divide_by_two(2)
#> [1] 1
library(ggplot2)
plot_diamonds <- function() {
p <- ggplot(head(diamonds), aes(x = cut, y = price)) +
geom_jitter()
res <- list(
name = "diamonds",
p = p
)
class(res) <- "diamonds"
``` r
# tidyeval for multiple arguments that can take multiple variables
library(dplyr)
# in the case where the verbs' arguments are ... e.g. group_by(), select(), use !!! within the function to expand the variables back out
# no enquo() or enquos() is needed because you will pass in a vars() call
group_select <- function(df, group_vars, select_vars){
df %>%
library(httr)
library(dplyr)
resp <- GET("https://summary-api.datamermaid.org/v1/sites/")
content <- jsonlite::fromJSON(content(resp, "text", encoding = "UTF-8"), simplifyDataFrame = TRUE)
as_tibble(content[["features"]])
@sharlagelfand
sharlagelfand / listcol_vs_tibble_col
Created September 23, 2019 22:38
list-col vs tibble-col?
library(tibble)
library(tidyr)
x <- tibble(a = 1,
b = 1:2,
c = 3:4)
x
#> # A tibble: 2 x 3
#> a b c
@sharlagelfand
sharlagelfand / testthat_analysis
Last active August 15, 2019 13:11
using testthat on data cleaning/derivation steps to ensure that they work as expected
# Deriving the "overall working status" of someone's employment positions
# in Ontario, where it is the highest of Full Time > Part Time > Casual.
# e.g. if someone has a full time and a part time position, their overall
# working status is full time. If they have two part time positions, it's part time.
library(dplyr)
sample_df <- tibble::tribble(
~id, ~working_status, ~province,
1, "Full Time", "Ontario",
1, "Casual", "Ontario",
@sharlagelfand
sharlagelfand / shiny_modules_reactlog_not_independent
Created July 12, 2019 03:55
shiny modules + reactlog + not independent
options(shiny.reactlog = TRUE)
library(shiny)
library(reactlog)
mod_iris_ui <- function(id) {
ns <- NS(id)
tagList(
fluidRow(
column(
not_equal <- function(a, b){
ifelse(a != b | is.na(a) | is.na(b),
ifelse(is.na(a) & is.na(b),
NA,
TRUE),
FALSE)
}
not_equal("A", "A")
#> [1] FALSE