x <- seq(-1,1,length=12) x x < 0 | x > 0.8 x < 0 & x > 0.8 x x[3] # extract the third element x[c(1,2,5)] # extract the first, second and fifth elements. x[-(3:10)] # extract all the elements except those in positions 3 to 10. x[ x > 0] # extract the elements that satisfy the condition. x[ x > 0 & x < 0.5] A <- cbind(c(1,2,-1), c(12,15,18), c(-1,-4,-9)) A A[1,1] #extracts the (1,1) element A[1,3] # extracts the (1,3) element A[1:2,3] #extracts the elements (1,3), (2,3) A[1:2,2:3] #extracts a two by two matrix A[,2:3] # omission of a dimension gives the corresponding columns A[-1,2:3] # use of negative indices mylist <- list(x,A) mylist mylist[[1]] mylist[[2]] library(MASS) is.data.frame(survey) names(survey) survey$Age[1:100] standard.deviation <- function(x) { sqrt(var(x)) } x <- rnorm(100, mean=0, sd=2) var(x) standard.deviation(x) random.gener <- function(n, distribution, shape) { if(distribution=="gamma") rgamma(n, shape) else if(distribution=="exp") rexp(n) else if(distribution=="norm") rnorm(n) else stop("Invalid Distribution") } random.gener(10, "gamma", 2) random.gener(10, "unif", 2) new.sign <- function(x) { for (i in 1:length(x)){ if(x[i] > 0) x[i] <- 1 else if(x[i] < 0) x[i] <- -1 } x } new.sign(-10:5) sgnfunction <- function(x) { ifelse(x > 0, 1, ifelse(x<0, -1, 0)) } sgnfunction(-10:10)