[R] Simple For Loop Help
gpetris
gpetris at uark.edu
Fri Mar 30 04:24:11 CEST 2012
Hi Arun,
This seems to do what you are looking for:
> Y <- matrix(rnorm(12), 4, 3)
> Y
[,1] [,2] [,3]
[1,] -1.0457177 0.7756343 -0.06063478
[2,] -0.8962113 1.5573704 -0.50137832
[3,] 1.2693872 -0.3654018 0.92606273
[4,] 0.5938409 0.8165564 0.03693769
> X <- apply(Y, 1, which.min)
> X
[1] 1 1 2 3
HTH,
Giovanni
Quoting "arun.gurubaramurugeshan" <arun.gurubaramurugeshan at Autozone.com>:
> 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.
More information about the R-help
mailing list