I have a data frame with a response variable, Y, and three factors, 'factor.a', 'factor.b', and 'factor.c'
I am trying to write a function that will
remove a columns from a data frame if all levels of the factor are the same
add the terms 'beta.factor.x[1..n]' to a vector of parameters when there is more than one level of a factor, up to 5 levels.
exclude the parameter beta.factor.b[1] from in the list (it is fixed)
Here is my code. I think it looks nice and works well, but I have read that it is best to avoid nested for loops, so I am curious if there is a more efficient approach.
data <- data.frame( y = c(1,2,3,4),
factor.a = c(1, 1, 2, 1),
factor.b = c(1, 2, 2, 3),
factor.c = c(0, 0, 0, 0))
model.parms <- list(factor.a = length(unique(data$factor.a)),
factor.b = length(unique(data$factor.b)),
factor.c = length(unique(data$factor.c)))
vars <- 'beta.o'
for (x in c('factor.a','factor.c', 'factor.b')) {
if(model.parms[[x]] == 1) {
data <- data[, -which(names(data) == x)]
} else {
m <- min(model.parms[[x]], 5)
for (i in 1:m) {
if(!i == 1 && x == 'factor.b') {
vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))
}
}
}
}