Skip to content

Instantly share code, notes, and snippets.

@aravindhebbali
Last active September 23, 2017 18:02
Show Gist options
  • Save aravindhebbali/26d85ab4a4dadd2fe7c1f58d854cc950 to your computer and use it in GitHub Desktop.
Save aravindhebbali/26d85ab4a4dadd2fe7c1f58d854cc950 to your computer and use it in GitHub Desktop.
Readable Code with R
# install
install.packages('magrittr')
install.packages('readr')
# library
library(magrittr)
library(readr)
# read data
ecom <- readr::read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/web.csv')
# view data
head(ecom, 10)
ecom %>% head(10)
# calculate square root
y <- ecom$n_pages
y <- sqrt(y)
y <- ecom %$% n_pages
y %<>% sqrt()
y <- ecom %$%
n_pages %>%
sqrt()
# calculate correlation
ecom1 <- subset(ecom, purchase == 'true')
cor(ecom1$n_pages, ecom1$duration)
ecom %>%
subset(purchase == 'true') %$%
cor(n_pages, duration)
# visualization
barplot(table(subset(ecom, purchase == 'true')$referrer))
ecom %>%
subset(purchase == 'true') %>%
extract('referrer') %>%
table() %>%
barplot()
# regression
summary(lm(duration ~ n_pages, data = ecom))
ecom %$%
lm(duration ~ n_pages) %>%
summary()
# string manipulation
email <- 'jovialcann@anymail.com'
toupper(strtrim(strsplit(email, '@')[[1]][1], 6))
email %>%
strsplit(split = '@') %>%
extract2(1) %>%
extract(1) %>%
strtrim(width = 6) %>%
toupper()
# extract column by name
head(ecom['n_pages'], 3)
ecom %>%
extract('n_pages') %>%
head(3)
# extract column by index
head(ecom[6], 3)
ecom %>%
extract(6) %>%
head(3)
# extract column as vector
head(ecom$n_pages)
ecom %>%
use_series('n_pages') %>%
head()
# extract list element by name
mt <- as.list(mtcars)
mt[['mpg']]
mt %>%
extract2('mpg')
# extract list element by index
mt[[1]]
mt %>%
extract2(1)
# extract list element as vector
mt$mpg
mt %>%
use_series(mpg)
# addition
1:10 %>%
`+`(1)
1:10 %>%
add(1)
# multiplication
1:10 %>%
`*`(3)
1:10 %>%
multiply_by(3)
# division
1:10 %>%
`/`(2)
1:10 %>%
divide_by(2)
# power
1:10 %>%
`^`(2)
1:10 %>%
raise_to_power(2)
# greater than
1:10 %>%
`>`(5)
1:10 %>%
is_greater_than(5)
# weakly greater than
1:10 %>%
`>=`(5)
1:10 %>%
is_weakly_greater_than(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment