## R as a calculator 5^2 + 100 ## assign a variable a value a = 5 # do calculations with a a*5 ## vectors b = numeric(3) b = c(1,1,1) b = rep(1,3) b = c(1, 2, 3) b = 1:3 d = 4:6 b*d # compute the mean of b (1 + 2 + 3)/3 # or sum(b)/3 # or mean(b) ## getting help about the function ?mean ## get certain elements in a vector b b[1] b[2:3] ## assign a new value b[1] = 20 b ## matrices m = matrix(1:6, nrow=2, ncol=3, byrow=T) m # sum the entries in each column colSums(m) # get the first row and second column entry m[1,2] # matrix multiplication m2 = matrix(c(2,3,2,1,4,2), nrow=3, ncol=2, byrow=T) m%*%m2 # does there a determinant function exist? m = matrix(1:4, 2,2) ??determinant det(m) # inverse of a matrix m = matrix(c(0.2, 0.7, 0.1, 0.7), 2,2, byrow=T) solve(m) # identity matrix of dimension 3 diag(3) solve(diag(2) - m) ## random numbers sample(1:5, 5, prob=c(0.1, 0.2, 0.5, 0.1, 0.1), replace=TRUE) ## sample from known distributions a = rnorm(1000) mean(a) var(a) hist(a, freq=F) ## if-statement w = 3 if(w > 2){ print("hei") } else { print("bye") } ## for-loop for(i in 1:10){ cat("hei", i, "\n") } n = 10 a = numeric(n) for(i in 1:n){ a[i] <- i + 5 } ## writing a function # my.mat : matrix you would like to multiply n-times with it self # n.times : number of times you would do matrix multiplication my.matrixMultiply = function(my.mat, n.times){ res.matrix = my.mat for(i in 1:n.times){ res.matrix = res.matrix %*% my.mat } return(res.matrix) } m = matrix(1:4, 2,2) my.matrixMultiply(m,2) m%*%m%*%m my.matrixMultiply(m,3) my.func2 = function(x){ return(x^2) } curve(my.func2(x), from=-5, to=5) curve(dnorm(x, mean=3, sd=1), from=-2, to=7) x = seq(from=-5, to=5, by=0.01) y = my.func2(x) plot(x,y, type="l") ## comparisons a = c(1,3,5) b = c(3,3,3) d = c(0,3,1) a > b a == b # elementwise comparison (a > b) & (a > d) # The longer form with two & evaluates left to right examining # only the first element of each vector. Evaluation proceeds # only until the result is determined. (a > b) && (a > d) # elementwise comparison (a >= b) | (a > d) # longer form (a >= b) || (a > d) ## some mathematical functions # modulo 10%%5 10%%6 # factorial factorial(3) # binomial coefficient choose(n=5, k=2)