Home > Software design >  Create new column with if else in R
Create new column with if else in R

Time:09-29

I have a database like this:

structure(list(code = c(1, 2, 3, 4), age = c(25, 30, 45, 50), 
car = c(0, 1, 0, 1)), row.names = c(NA, -4L), class = c("tbl_df", 
  "tbl", "data.frame"))

I want to create a column "drivers under 40" with this conditions:

  • 0 if Age<40 & car==0
  • 1 if Age<40 & car==1

How do I create the third column with this conditions? I tried using the code "if else" to create a variable but it doesn't work.

drivers <- ifelse((age <= 40) & (car==0), 0, ifelse((age<=40) & (car==1), 1))

Is maybe the code written wrong? Is there another method to do it? I am afraid to mess up the parentheses so I'd prefer another method, if there is any faster

CodePudding user response:

Here is a dplyr version with case_when

library(dplyr)
df %>% 
  mutate(drivers_under_40 = case_when(age <= 40 & car==0 ~ 0,
                                      age <= 40 & car==1 ~ 1,
                                      TRUE ~ NA_real_))
  code   age   car drivers_under_40
  <dbl> <dbl> <dbl>            <dbl>
1     1    25     0                0
2     2    30     1                1
3     3    45     0               NA
4     4    50     1               NA

CodePudding user response:

A base R option

df1$drivers_under_40 <-  with(df1, (age <= 40 & car == 1)* NA^(age> 40))
df1$drivers_under_40
[1]  0  1 NA NA

CodePudding user response:

Unless you work with dplyr you have to specify the data in your ifelse statement. data$column for example. Also you have to assign a new column for the operation. And the last else-statement is missing.

so your ifelse statement should look like this:

data = structure(list(code = c(1, 2, 3, 4), age = c(25, 30, 45, 50), 
               car = c(0, 1, 0, 1)), row.names = c(NA, -4L), class = c("tbl_df", 
                                                                       "tbl", "data.frame"))

data$drivers <- ifelse((data$age <= 40) & (data$car==0), 0, ifelse((data$age<=40) & (data$car==1), 1, "here you have to fill another 'else' value"))
  • Related