R Misc Flashcards
What is the package that allows you to do ridge regression and lasso regression
library(‘glmnet’)
How to implement CV when you are doing linear or logistics regression?
cv.glmnet() is a function that will do CV for you.
Does glmnet library have predict function? What is glmnet for?
yes, it does however the regsubsets (for best subset, forward and backward LR) function does not have one.
Also glmnet is for lasso and ridge regression
How to conduct lasso regression
library(glmnet) # Do CV to get best tuning paramter # Use alpha = 1 for lasso cv.out = cv.glmnet(x[train, ], y[train], alpha = 1) bestlam = cv.out$lambda.min
Print out character array one letter at at a time by looping
x = c(‘a’, ‘b’, ‘c’)
for(letter in x) {
print(letter)
}
if control structure R
if() { ## do something } else if() { ## do something different } else { ## do something different }
easiest to initiate an infinite loop (on purpose)
repeat{
if(condition) {
break
}
}
how to skip an interation in a loop
Use next for(i in 1:100) { if(i <= 20) { ## Skip the first 20 iterations next } ## Do something here }
while loops
while(count < 10) {
print(count)
count <- count + 1
}
How to make a function
f ) { ## Do something interesting }
get list of arguments for a function
args()
ex: args(lm)
describe the lazy evaluations of functions
Arguments to functions are evaluated lazily, so they are evaluated only as needed.
f <- function(a, b) {
a^2
}
f(2)
This function never actually uses the argument b, so calling f(2) will not produce an
error because the 2 gets positionally matched to a.
What does … mean in a function defintion
- when extending another function, but don’t want to copy entire argument list
- … so that extra arguments can be passed to methods
- … is necessary when the number of arguments cannot be known in advance, such as paste() and cat.
Display the list of environment variables and packages R will iterate through to find a variable, in the order they will be searched
search()
When user loads a library, where does it go on the search list?
it goes into second place, everything else goes down 1. the global environment of the users workspace is always number 1