-1

I have never used for loops before and I would like to use it for my data. However, I still don't know how to use it properly. Could anyone tell me how to use for loops correctly?

 For item 1 to 9 
 the results I wanted to get
real<lower=0>l1_0+l1_11
real<lower=0>l2_0+l2_11
real<lower=0>l3_0+l3_11
 ..
real<lower=0>l9_0+l9_11

For item 10 to 18
real<lower=0>l10_0+l10_12
real<lower=0>l11_0+l11_12
real<lower=0>l12_0+l12_12
..  
real<lower=18>l18_0+l18_12


  What I tried to do..
  for(i in 1:9){
  i=l[i]"_0"+l[i]"_11"
  print(paste("real<lower=0>",i))
  }

  for (i in 1:9){
  i<-paste('l',i,'_0',sep='')
  print(paste("real<lower=0>",i)
  }
Newuser
  • 45
  • 3
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. I'm not sure what you've written is meant to be code or string values. – MrFlick Feb 05 '20 at 18:12
  • 1
    `paste` is vectorized, so you probably do not need a loop. `paste0("reall", 1:18, "_0+l",1:18, "_1", nchar(1:18))` – AndS. Feb 05 '20 at 18:37

1 Answers1

0

Assuming you have no background in programming and just want to know how to use the for loop. I have created a very simple data-frame and will do something easy. I want to have the sum of each row in the data-frame (luckily we also have the apply family to do this simply).

df <- data.frame(x=c(1,4,2,6,7,1,8,9,1),
                 y=c(4,7,2,8,9,1,9,2,8))

This is the example shown everywhere, which is highly unsatisfactory.

for(i in 1:10){
  print(i)
}

Only print the example of the sum of each row.

for(i in 1:nrow(df)){
  print(df$x[i]+df$y[i])
}

This is the part often horrible explained everywhere (I do not get why? Perhaps I just used the wrong searching terms/keywords?). Fortunately, there was a good example here on Stack Exchange that showed me how. So, the credits go to someone else. Yet, this part is fairly easy, but for someone with no background in modeling, R, or any programming what so ever, it can be an pain in the ass to figure out. To make a for loop and store the results, you NEED to create an object that can store the data of the loop.

Here a simple for loop storing the results in a data frame.

loopdf <- as.data.frame(matrix(ncol = 1, nrow = 0))
for(i in 1:nrow(df)){
  loopdf[i,] <- df$x[i]+df$y[i]
}
loopdf

Here a simple for loop storing the results in a list.

looplist <- list()
for(i in 1:nrow(df)){
  looplist[[i]] <- df$x[i]+df$y[i]
}
do.call(rbind, looplist)

Here a loop concatenating the results in an atomic vector.

loopvec <- NULL
for(i in 1:nrow(df)){
  loopvec <- c(loopvec, df$x[i]+df$y[i])
}

loopvec

Here the apply loop (two versions).

apply(df, 1, sum)
apply(df, 1, function(x), sum(x))