vendredi 3 décembre 2021

If, else if and else syntax within for loop in R

This is the sample dataframe I'm working with:

numbers <- data.frame(value=c(-5000,1,2,100,200,300,400,500, 1000, 2000, 10000, 12000))

I'm looking to create a new column in this data frame called "output" that contains values as follows:
-Same value as in column "value" if value between 1 and 10000
-10000 if the value in column "value" is more than 10000 and
-1 if the value in column "value" is less than 1

Desired output in the new column "output": 1,1,2,100,200,300,400,500, 1000,2000, 10000, 10000.

I would really like to learn how to use for loop, if, else if and else statements to get this output and have tried the following:

for (i in 1:nrow (numbers$value)){
  if (numbers$value[i] >10000){
    numbers$output <- 10000)
  } else if (numbers$value[i] < 1){
    numbers$output <- 1)
  } else {
    numbers$output <- numbers$value)
  }
}

Unfortunately, this gives me an error, Error: unexpected '}' in "}"

Appreciate your help in fixing this code!

Aucun commentaire:

Enregistrer un commentaire