Noga Carmon
Noga Carmon

Reputation: 1

Adding new column with conditional values using if-else [R]

I don't understand why the code isn't working. I want to add a column which for a 1/3 value of my data in a different column will write "Low", and for the 2/3 of the data "Medium", and for the rest "High":

OWL_DIET$skull_lenth_w_factor            = c(OWL_DIET$skull_length * 1.5)       

first_third                              <- (max(OWL_DIET$skull_lenth_w_factor))/3             
second_third                             <- (2*(max(OWL_DIET$skull_lenth_w_factor)))/3     

OWL_DIET$Level                           <- 1
i                                        <- 1

for (val in OWL_DIET$Level) {if (OWL_DIET$skull_lenth_w_factor[i] < first_third)
{OWL_DIET$Level[i] <- "Low" } else if (OWL_DIET$skull_lenth_w_factor[i] < second_third) 
    {OWL_DIET$Level[i] <- "Medium" } else data$Level[i] <- "High" i <- i + 1}

Upvotes: 0

Views: 194

Answers (1)

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21442

Use nested ifelseinstead of the forloop:

Reproducible data:

set.seed(123)
df <- data.frame(
  val = rnorm(50, 10))

Solution:

df$group <- ifelse(df$val <= 9, "LOW",
                   ifelse(df$val <= 11, "MEDIUM", "HIGH"))

Result:

df
         val  group
1   9.439524 MEDIUM
2   9.769823 MEDIUM
3  11.558708   HIGH
4  10.070508 MEDIUM
5  10.129288 MEDIUM
6  11.715065   HIGH
7  10.460916 MEDIUM
8   8.734939    LOW
9   9.313147 MEDIUM
10  9.554338 MEDIUM
11 11.224082   HIGH
12 10.359814 MEDIUM
13 10.400771 MEDIUM
14 10.110683 MEDIUM
15  9.444159 MEDIUM
16 11.786913   HIGH
17 10.497850 MEDIUM
18  8.033383    LOW
19 10.701356 MEDIUM
20  9.527209 MEDIUM
21  8.932176    LOW
22  9.782025 MEDIUM
23  8.973996    LOW
24  9.271109 MEDIUM
25  9.374961 MEDIUM
26  8.313307    LOW
27 10.837787 MEDIUM
28 10.153373 MEDIUM
29  8.861863    LOW
30 11.253815   HIGH
31 10.426464 MEDIUM
32  9.704929 MEDIUM
33 10.895126 MEDIUM
34 10.878133 MEDIUM
35 10.821581 MEDIUM
36 10.688640 MEDIUM
37 10.553918 MEDIUM
38  9.938088 MEDIUM
39  9.694037 MEDIUM
40  9.619529 MEDIUM
41  9.305293 MEDIUM
42  9.792083 MEDIUM
43  8.734604    LOW
44 12.168956   HIGH
45 11.207962   HIGH
46  8.876891    LOW
47  9.597115 MEDIUM
48  9.533345 MEDIUM
49 10.779965 MEDIUM
50  9.916631 MEDIUM

Upvotes: 1

Related Questions