[R] Simple For Loop Help

J Toll jctoll at gmail.com
Fri Mar 30 01:56:43 CEST 2012


On Thu, Mar 29, 2012 at 4: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.


Arun,

I think you want something along the lines of:

> x <- matrix(rnorm(30), nrow = 10)
> x
            [,1]        [,2]        [,3]
 [1,] -2.1650589  1.94859071 -0.45721676
 [2,] -1.4667920  2.34222583  1.17776076
 [3,] -0.2807439  0.09512075  0.61303958
 [4,] -0.1449027  0.56009407  1.03240104
 [5,]  0.9955293  0.85945217 -0.06094224
 [6,]  0.6380514 -0.49667348  0.12532813
 [7,] -0.4096329 -0.96153212 -0.44399899
 [8,] -0.5364318 -0.62121738 -1.42266665
 [9,] -0.7713245 -0.69132827 -0.48067279
[10,]  1.0515935  0.47035874 -1.17460809
> x <- cbind(x, apply(x, 1, function(row) which(row == min(row))))
> x
            [,1]        [,2]        [,3] [,4]
 [1,] -2.1650589  1.94859071 -0.45721676    1
 [2,] -1.4667920  2.34222583  1.17776076    1
 [3,] -0.2807439  0.09512075  0.61303958    1
 [4,] -0.1449027  0.56009407  1.03240104    1
 [5,]  0.9955293  0.85945217 -0.06094224    3
 [6,]  0.6380514 -0.49667348  0.12532813    2
 [7,] -0.4096329 -0.96153212 -0.44399899    2
 [8,] -0.5364318 -0.62121738 -1.42266665    3
 [9,] -0.7713245 -0.69132827 -0.48067279    1
[10,]  1.0515935  0.47035874 -1.17460809    3

HTH,

James



More information about the R-help mailing list