Skip to content

Instantly share code, notes, and snippets.

@aaronsaunders
Created August 6, 2013 16:01
Show Gist options
  • Save aaronsaunders/6165860 to your computer and use it in GitHub Desktop.
Save aaronsaunders/6165860 to your computer and use it in GitHub Desktop.
1:10
c(1, 2, 3, 4)
seq(1, 10, 1)
seq(from=1, to=10, by=1)
sequence(c(10, 5))
seq(along.with=myData) # makes seq of 1:length(myData))
seq(10, along.with=myData) # makes seq of 10:length(myData))
seq(from=2, length.out=10)
rep(x, times = 1, length.out = NA, each = 1)
rep(1:5, 2) # repeat sequence 1 to 5, 2 times
# [1] 1 2 3 4 5 1 2 3 4 5
rep(1:5, each = 2)
#[2] 1 1 2 2 3 3 4 4 5 5
rep(1:4, each = 2, times = 3)
#[1] 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4
rep(1:4, c(2,1,2,1)) # also takes a vector for "number of times"
#[3] 1 1 2 3 3 4 5 5
rep(1:4, each = 2, len = 4) # truncate seq at len
#Generate levels
gl(n,repeat,length=n*k,labels=1:n)
gl(3,4) # 3 levels repeated 4 times
# [1] 1 1 1 1 2 2 2 2 3 3 3 3
#Levels: 1 2 3
gl(2, 6, label=c("Male", "Female"))
# [1] Male Male Male Male Male Male
# [7] Female Female Female Female Female Female
# Levels: Male Female
factor(1:3)
# [1] 1 2 3
Levels: 1 2 3
factor(1:3, levels=1:5)
# [1] 1 2 3
# Levels: 1 2 3 4 5
factor(1:3, levels=rev(1:5))
# [1] 1 2 3
# Levels: 5 4 3 2 1
a <- factor(1:3, labels=c("A", "B", "C"))
# [1] A B C
# Levels: A B C
levels(a)
# [1] "A" "B" "C"
nlevels(a)
# [1] 3
###########################
#Random sequences
#Random fractions
runif(n, min=0, max=1)
runif(4) # default between 0 and 1
#[1] 0.2730056 0.3908863 0.3922892 0.6863782
# Random integers
sample(1:10, 4) # replace = F (by default)
#[1] 5 8 10 6
sample(1:10, 5, replace=T)
#[1] 4 3 3 10 8
#Gaussian (normal)
rnorm(n, mean=0, sd=1)
rnorm(10, mean=0, sd=1)
#[1] -0.9975093 1.4343867 -0.6368257 -0.7647334 -0.2932963 1.6560540 0.6182828
#[8] 1.0377166 1.3144655 0.6245061
mat.1K <- replicate(6, rnorm(1000, mean=5, sd=1))
#Poisson
rpois(n, lambda)
#`Student' (t)
rt(n, df)
#Pearson (X^2)
rchisq(n, df)
#binomial
rbinom(n, size, prob)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment