I have this for loop for creating a list of variables:
vars <- c( 'beta.o', 'sd.y')
for (x in c('ghs', 'site', 'trt')) {
if(model.parms[[x]] == 1) {
data <- data[, which(names(data) != x)]
} else {
data <- data
if(x!='ghs') {
vars <- c(vars, paste('sd.', x, sep = ''))
}
m <- min(model.parms[[x]], 5)
for (i in 1:m) {
if(i == 1 && x == 'site') {
vars <- c(vars, 'beta.site[1]')
}
if (i > 1) {
vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))
}
}
}
}
It has been bothering me terribly, and I have failed the last two times I have tried to replace it, although conceptually it should be able to be written in a few lines. Any advice?
2 Answers 2
This bit:
for (i in 1:m) {
if(i == 1 && x == 'site') {
vars <- c(vars, 'beta.site[1]')
}
if (i > 1) {
vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))
}
}
Says handle the first pass differently from all the others. So I would replace it with this:
if (x == 'site') {
vars <- c(vars, 'beta.site[1]')
}
for (i in 2:m) {
vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))
}
The big mistake in your code is you are dynamically growing your vectors. For example, compare
x = NULL
for(i in 1:100000)
x = c(x, i)
with
x = numeric(100000)
for(i in 1:100000)
x[i] = i
The other key point is that paste
function can be vectorised. So,
for (i in 1:m) {
if(i == 1 && x == 'site') {
vars <- c(vars, 'beta.site[1]')
}
if (i > 1) {
vars <- c(vars, paste('beta.', x, '[', i, ']', sep=''))
}
}
can be replaced with
if(x == 'site') {
vars <- c(vars, 'beta.site[1]')
}
vars = c(vars, paste('beta.', x, '[', i, ']', sep=''))