i get a problem in if, else if statment....

I want to write a R programme and create a column in a dataframe by following this rules:
salary < q25, lv=low
salary >=q25 or salary < 75, lv=mid
salary > q75, lv=high

i already got q25 and q75 and i am using package and mutate to add a column about salary lv.

There are the programme.

C_new = mutate(C_sample,
lv=
for(i in C_sample$salary){
if(C_sample$salary < q30){
lv="Low"
}else if(C_sample$salary > q70){
lv="High"
}else{
lv="Mid"
}
})

Rstudio said that there were 50 or more warnings (use warnings() to see the first 50).....

how do i sovle the problem...

R formulas are typically "vectorized," which means you don't need to loop through the rows to apply the function to all of them.

I expect something like this should work. The %>% and case_when functions in dplyr can help make the code more readable.

C_new <- C_sample %>%
   mutate(lv = case_when(salary < q25 ~ "low",    
                         salary < q75 ~ "medium",
                         TRUE         ~ "high"))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.