Find pattern in x and replace with replacement text. If fixed=FALSE then pattern is a regular expression. If fixed = T then pattern is a text string.
sub("\s",".","Hello There") returns "Hello.There"
Split the elements of character vector x at split.
strsplit("abc", "") returns 3 element vector "a","b","c"
Concatenate strings after using sep string to seperate them.
paste("x",1:3,sep="") returns c("x1","x2" "x3")
paste("x",1:3,sep="M") returns c("xM1","xM2" "xM3")
paste("Today is", date())
Statistical Probability Functions
The following table describes functions related to probaility distributions. For random number generators below, you can use set.seed(1234) or some other integer to create reproducible pseudo-random numbers.
normal density function (by default m=0 sd=1)
# plot standard normal curve
x <- pretty(c(-3,3), 30)
y <- dnorm(x)
plot(x, y, type='l', xlab="Normal Deviate", ylab="Density", yaxs="i")
cumulative normal probability for q
(area under the normal curve to the left of q)
pnorm(1.96) is 0.975
value at the p percentile of normal distribution
qnorm(.9) is 1.28 # 90th percentile
n random normal deviates with mean m
and standard deviation sd.
#50 random normal variates with mean=50, sd=10
x <- rnorm(50, m=50, sd=10)
binomial distribution where size is the sample size
and prob is the probability of a heads (pi)
# prob of 0 to 5 heads of fair coin out of 10 flips
dbinom(0:5, 10, .5)
# prob of 5 or less heads of fair coin out of 10 flips
pbinom(5, 10, .5)
uniform distribution, follows the same pattern
as the normal distribution above.
#10 uniform random variates
x <- runif(10)
Other Statistical Functions
Other useful statistical functions are provided in the following table. Each has the option na.rm to strip missing values before calculations. Otherwise the presence of missing values will lead to a missing result. Object can be a numeric vector or data frame.
mean of object x
# trimmed mean, removing any missing values and
# 5 percent of highest and lowest scores
mx <- mean(x,trim=.05,na.rm=TRUE)
standard deviation of object(x). also look at var(x) for variance and mad(x) for median absolute deviation.
quantiles where x is the numeric vector whose quantiles are desired and probs is a numeric vector with probabilities in [0,1].
# 30th and 84th percentiles of x
y <- quantile(x, c(.3,.84))
lagged differences, with lag indicating which lag to use
scale(x, center=TRUE, scale=TRUE)
column center or standardize a matrix.
Other Useful Functions
seq(from , to, by)
generate a sequence
indices <- seq(1,10,2)
#indices is c(1, 3, 5, 7, 9)
repeat xn times
y <- rep(1:3, 2)
# y is c(1, 2, 3, 1, 2, 3)
divide continuous variable in factor with n levels
y <- cut(x, 5)