[R] Simple For Loop Help

jim holtman jholtman at gmail.com
Fri Mar 30 01:58:36 CEST 2012


tyr this:

> # generate some data
> x <- cbind(y1 = runif(100)
+          , y2 = runif(100)
+          , y3 = runif(100)
+          )
>
> x <- cbind(x, y4 = apply(x, 1, which.min))
> x
                y1            y2          y3 y4
  [1,] 0.976953289 0.91072645970 0.713624001  3
  [2,] 0.630992512 0.49545109738 0.492651173  3
  [3,] 0.805360855 0.10164273344 0.487412602  2
  [4,] 0.206557258 0.93518137769 0.967720379  1
  [5,] 0.742643551 0.01508265687 0.184230089  2
  [6,] 0.273187587 0.96277903509 0.975695134  1
  [7,] 0.531257896 0.28845930938 0.884927711  2
  [8,] 0.443350543 0.83843108499 0.932529126  1
  [9,] 0.741068321 0.18445303664 0.918877386  2
 [10,] 0.702316870 0.33005132875 0.873039624  2
 [11,] 0.344680035 0.01381954318 0.317793813  2
 [12,] 0.458753836 0.87229841063 0.744396384  1
 [13,] 0.843603048 0.54047069070 0.450843775  3
 [14,] 0.409279518 0.63338707620 0.776766221  1
 [15,] 0.352133089 0.50061018439 0.807262663  1
 [16,] 0.560342140 0.45078424131 0.885666004  2


On Thu, Mar 29, 2012 at 5:32 PM, arun.gurubaramurugeshan
<arun.gurubaramurugeshan at autozone.com> wrote:
> Hi,
> I need help with the following.
>
> I have a dataset Y with 200 observations and three variables Y1, Y2 & Y3. I
> have to find the minimum of Y1, Y2 & Y3 and if the minimum is Y1 then I have
> to assign 1 to a variable (Y4), if Y2 is the minimum then "2" to Y4  else
> "3" to Y4. This is what I have done....
>
> for (i in 1:200) if(Y1<Y2 & Y1<Y3) Y$Y4=1 else if (Y2<Y3) Y$Y4=2
> else Y$Y4=3
>
> and R is throwing back this warning message
>
> Warning messages:
> 1: In if (Y1 < Y2 & Y1 < Y3) Y4 <- 1 else if (Y2 < Y3) Y4
> <- 2 else Y4 <- 3 :
>  the condition has length > 1 and only the first element will be used
> 2: In if (Y2 < Y3) Y4 <- 2 else Y4 <- 3 :
>  the condition has length > 1 and only the first element will be used
>
> Any help would be appreciated.
>
> Thanks
> Arun
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Simple-For-Loop-Help-tp4517088p4517088.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.



More information about the R-help mailing list