########## # Lecture 7 # Andrew Jaffe # ex1 x = rnorm(1000) pos = rep(0,1000) for(i in seq) { if(x[i] > 0) { pos[i] = 1 } else { pos[i] = 0 } # ex 2 Indexes = list() for(i in 1:10) { Indexes[[i]] = 1:i } out = rep(NA, 10) for(i in 1:10) { Index = Indexes[[i]] # only do something with a certain # number of observations - here, 4 if(length(Index) > 3) { out[i] = sum(Index) } } # ex3 # tests if a number if positive pos = function(x) { if(x >= 0) out = 1 if(x < 0) out = 0 return(out) } y = pos(4) # protected x = 3 pos(6) x pos = function(x,verbose=TRUE) { if(x >= 0) out = 1 if(x < 0) out = 0 if(verbose) cat("finished running","\n") return(out) } y = pos(5) for(i in 1:1e5) { if(i %% 10000 == 0) cat(".") # do other stuff } require(RColorBrewer) mypar <- function(a=1,b=1,brewer.n=8,brewer.name="Dark2",...){ par(mar=c(2.5,2.5,1.6,1.1),mgp=c(1.5,.5,0)) par(mfrow=c(a,b),...) palette(brewer.pal(brewer.n,brewer.name)) } summ <- function(a,b) { out = a+b return(out) } prodd <- function(a,b,c) { out = a*b*c return(out) }