# Welcome to R! # Basics 1 + 2 2 * 3 4 / 3 # this is a comment 1:5 for (i in 1:10) { print(i) } array <- 2:7 print(array) round(3.1) ceiling(3.1) floor(3.1) factorial(3) factorial(10) mean(3:8) mean(array) sample(1:10, 3, replace=TRUE) args(sample) help(sample) my_function <- function(arr) { for (i in arr) { print(i) } } sample(1:10, 11, replace=TRUE) my_function(array) # Sets install.packages('sets') library(sets) a <- set(1, 2, 3) b <- set(1, 2, 3, 4, 5) c <- as.set(2:7) print(a) print(b) is.set(a) set_is_empty(b) set_is_empty(set()) a | b # union b - a # difference a & b # intersection a * b # cartesian product a < b # subset length(a) # cardinality a == b # equal 2^a # power set set_combn(b, 3) mean(b) # Probability Distributions # prefixes # d = PMF # p = CMF # r = simulations (random) # suffixes # binom(x, size=, p=) # geom(x, prob=) # norm(x, mean=, sd=) # pois(x, lambda=) # exp(x, rate) # PMF of binomial measure where x = 1, n = 2, p = 0.5 dbinom(1, size=2, prob=0.5) # Binomial Distribution n <- 10 p <- 1/2 x <- 0:n pmfbinom <- dbinom(x, size=n, prob=p) pmfbinom plot(c(1, 2, 3, 4, 5), c(1, 4, 9, 16, 25)) plot(x, pmfbinom, main=sprintf("PMF Binomial Distribution, n = %s p = %s", n, p)) plot(x, pbinom(x, size=n, prob=p), main=sprintf("CMF Binomial Distribution, n = %s p = %s", n, p)) draws <- rbinom(x, size=n, prob=p) draws hist(draws, breaks=(0:n+1)-0.5, main=sprintf("random draws from bin(n = %s, p = %s)", n, p), probability=TRUE) points(x, pmfbinom) # geometric dist, prob = 1/3 args(dgeom) plot(dgeom(0:10, prob=1/3)) # normal dist, mu = 0, sd = 1 args(dnorm) plot(dnorm(-5:5, mean=0, sd=1)) # poisson dist, lambda = 2 args(dpois) plot(dpois(0:10, lambda=2)) args(dexp) plot(dexp(0:10, rate=0.5)) # Combinations and Permutations install.packages("combinat") library(combinat) args(combn) # combinations of all elements of vector x taken m at a time args(permn) # permutations of all elements of vector x # sample() c <- combn(1:5, 2) p <- permn(1:3) length(p) dim(c)[2] c p