2
\$\begingroup\$

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?

asked Mar 24, 2011 at 21:13
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

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=''))
}
answered Mar 24, 2011 at 22:14
\$\endgroup\$
0
1
\$\begingroup\$

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=''))
answered Feb 15, 2012 at 10:00
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.