-1

I have a for loop with a control structure using internal for loops.

for (x in 1:100)){
      for(y in 1: 10){
          for(z in 1:(100/10)){
          return as.factor(y)     
          }
      }
  }

Is it possible to make this into a sapply or does sapply only work with one loop control. I have searched this site and the web but I have not seen any reference to a more complex control structure using sapply than just one counter

no name
  • 245
  • 2
  • 14
  • 3
    What is the wider context of what you are trying to achieve here? There could (is likely) be a better way. – Simon O'Hanlon Oct 18 '13 at 17:18
  • You're not using `x` or `z` indices here. Is there a reason you're looping over them? – Señor O Oct 18 '13 at 17:24
  • 1
    You can nest `sapply()` calls, just like for loops, but that isn't going to be quicker unless your loops are poorly written to start with. The real question is if three levels of nesting are needed... but I would need more information to understand what your loop does before commenting on that. – David Oct 18 '13 at 17:25
  • Basically, I am trying to return y as factor. I am trying to label residuals to a group for a Hosmer-Lemshow goodness of fit test using box plots. So, I have n observations, y, groups, and n/y observations in each group so the group number is z repeated y number of times – no name Oct 18 '13 at 17:30
  • @GlennSchultz Why don't you show some sample input data and some desired output data. Not your real data, just enough sample data that it adequately describes the gist if what you are trying to achieve. Please read [**how to make a great reproducible example**](http://stackoverflow.com/q/5963269/1478381) for tips. – Simon O'Hanlon Oct 18 '13 at 17:36
  • I think I am making this too complex if I have x = 10, y = 5, then the vector z should be 1122334455. The function is supposed to make the data. – no name Oct 18 '13 at 18:12
  • That it johnny, I would never have thought to use paste - clever – no name Oct 18 '13 at 19:54

1 Answers1

1

If I correctly understand the question, x specifies total vector length and y number of repetitions for the integers. Then

z <- paste(sort(rep(1:y,x/y)), collapse="")

This returns a character. You can use as.numeric() to convert it to a number.

johnny
  • 156
  • 1
  • 5