mercredi 19 avril 2017

How to use if...else if function to divide numeric variable into groups in R and also the less than and equal operator show errors

I have two basic problems with R code as the title.

Suppose I have a dataset like:

 w <- c( 0.005810275, -0.002758455, -0.005423105, -0.006692736, -0.010571356, 
        -0.006818535, -0.006943209, -0.004355057, -0.005951043, -0.002172708, 
        -0.003631478, -0.003957327, -0.005285497, -0.007682379, -0.007746185, 
        -0.011307843, -0.014013202, -0.013537595, -0.012859406, -0.013629170)

And I try to divide them into 4 groups, thus wrote the code as following:

 n=20
group <- rep(0,n)

for (i in 1:n){
    if (W[i] <= -0.05) { group[i]=1}
    else if ( -0.05 < W[i] <= -0.03  ) {group[i]=2}
    else if (-0.03 < W[i] <= -0.01) {group[i]=3}
    else group[i]=4
}

The error message is as following:

> group <- rep(0,n)
> for (i in 1:n){
+   if (W[i] <= -0.05) { group[i]=1}
+   else if ( -0.05 < W[i] <= -0.03  ) {group[i]=2}
Error: unexpected '<=' in:
"  if (W[i] <= -0.05) { group[i]=1}
      else if ( -0.05 < W[i] <="
>   else if (-0.03 < W[i] <= -0.01) {group[i]=3}
Error: unexpected 'else' in "  else"
>   else group[i]=4
Error: unexpected 'else' in "  else"
> }
Error: unexpected '}' in "}"

I really do not know why "<=" is an error.

Is there anyone could help? Thank you so much! BTW I use RStudio.

Aucun commentaire:

Enregistrer un commentaire