Home > Software engineering >  Create a new variable in a dataset from another variable
Create a new variable in a dataset from another variable

Time:03-04

I would like to know how from the variables of a dataset I can create another variable that takes values from the value contained in another variable. That is to say, I have an available variable called "age" that contains integral values with the ages of people. Therefore, I want to create a variable in this dataset called "education", so that if age is less than 7, education takes the value "primary education". If age is between 7 and 12, education takes the value "secondary education". Any idea how I can do this?

I've tried to do something like the following but I do not get results

if ((df$age) < 7){
  df$education="primary education"
}

CodePudding user response:

Here is a solution using the tidyverse and more specifc the dplyr package

library(dplyr)

# create example data by sampling random ages
df <- data.frame(age = sample(x = 5:21, size = 100, replace = TRUE))

# classify age into education col
df <- dplyr::mutate(df, education = dplyr::case_when(age < 7 ~ "primary education", 
                                                     age >= 7 & age < 12 ~ "secondary education", 
                                                     age >= 12 ~ "other"))

CodePudding user response:

With base R, you can use the ifelse command for element-wise conditions:

df$education <- ifelse(df$age < 7, "primary education", "secondary education")

You can nest ifelse statements to obtain more levels (although not very elegantly):

df$education <- ifelse(df$age < 7, "primary education",
                       ifelse(df$age >= 7 & df$age < 12, "secondary education"), "other")
  •  Tags:  
  • r
  • Related