0

Let's say I have the code below:

data = data.frame(x=numeric(), y=numeric(), z=numeric(), ans=numeric())

x = rnorm(10,0,.01)
y = rnorm(10,0,.45)
z = rnorm(10,0,.8)

ans = x+y+z

data = rbind(data,  data.frame(x=x, y=y, z=z, ans=ans)) 

example = function(ans) {
  ans^2
}

data$result = example(data$ans)

I want to use a while loop to assess the ans column of the dataframe and if all of the numbers in the column are less than 0 perform the example function on the ans column. If they are not all below 0 I would like it to run again until they are. Any help is appreciated.

adaml768
  • 29
  • 1
  • 7
  • Is there a reason you want to run a while loop here? Are you trying to solve a real problem or just trying different stuff? There are very few cases when someone will need to use a `while` loop in R if any. – David Arenburg Jul 28 '15 at 18:26
  • I am using this for an actual code that has a lot more to it. It still may not need a while loop but that was just the best way I could think of. – adaml768 Jul 28 '15 at 18:31
  • So you are using bad practices then. R is a vectorized language and you simple don't run a while loop in order to perform the most basic subsetting operation. – David Arenburg Jul 28 '15 at 18:33
  • I am open to learning how to do it better. I edited the question a bit (may still not need a while loop) but that is more accurate to what I am trying to do. – adaml768 Jul 28 '15 at 18:52
  • I must stay that now when reading the accepted answer he did a completely different thing from what you have described. You never mentions the `x` column or that you want keep modifying it using `rnorm`, @scoa probably has some mind reading skills. – David Arenburg Jul 28 '15 at 19:13
  • I just edited the question. He did answer what it asked at first. – adaml768 Jul 28 '15 at 19:15
  • Even if so, where did you mention that you want to keep modifying the `x` column using `rnorm` in each iteration? – David Arenburg Jul 28 '15 at 19:17

1 Answers1

1

You can use any to test whether there are negative x values.

data = data.frame(x=rnorm(10,0,.01),
                  y = rnorm(10,0,.45),
                  z = rnorm(10,0,.8))
while(any(data$x >= 0)){
  data$x[data$x >= 0] <- rnorm(length(data$x[data$x >= 0]),0,.01)
}
data$ans = x+y+z

print(data)

               x           y          z        ans
1  -0.0014348613  0.51931771 -0.4695617  1.2199625
2  -0.0037155145 -0.72322260  0.4650501  2.2660665
3  -0.0007619743  0.42842295 -0.3660313  0.2690932
4  -0.0068680912  0.36888855  1.4445536  0.6955025
5  -0.0134698425 -0.17174076 -1.2325956  0.7463931
6  -0.0029502825 -0.04208495 -1.4656484 -0.7020727
7  -0.0027566384  0.09476311 -0.1328970 -0.1437156
8  -0.0188576808 -0.25938843 -0.6648152  0.4843587
9  -0.0013769550 -0.00792926  0.4946057 -2.1885040
10 -0.0026376453 -0.15831996 -0.1263073 -0.2611772
scoa
  • 19,359
  • 5
  • 65
  • 80