简体   繁体   中英

Create a new variable with 4 levels

I have two variables in my dataset and I want to combine college_grad and sex to create sex_grad . The levels should be as follows:

  • Male Graduate
  • Female Graduate
  • Male Non-graduate
  • Female Non-graduate

collegegrad has two levels:

  • Yes
  • No

sex has two levels:

  • Male
  • Female

How should I approach the required combination to support 4 levels? I know how to use mutate along with ifelse , but that creates only two variables.

Use paste instead of ifelse .

college_grad = c("Graduate", "Non-graduate")
sex = c("Male", "Female")
df <- expand.grid(college_grad = college_grad, sex = sex)
df$sex_grad <- with(df, paste(sex, college_grad))
df

#   college_grad    sex            sex_grad
# 1     Graduate   Male       Male Graduate
# 2 Non-graduate   Male   Male Non-graduate
# 3     Graduate Female     Female Graduate
# 4 Non-graduate Female Female Non-graduate

Edit : This one corresponds to your edit.

college_grad = c("Yes", "No")
sex = c("Male", "Female")
df <- expand.grid(college_grad = college_grad, sex = sex)
df$sex_grad <- with(df, ifelse(college_grad == "Yes", paste(sex, "Graduate"), paste(sex, "Non-graduate")))
df

By combine you might mean a couple of things. Without a dataset to work with and an example of what output you want it's a bit harder to answer your question.

If you want to add the columns together, and keep all existing columns, then:

library(tidyverse)

mtcars %>% 
  mutate(
    mpg_am = mpg + am 
  )

If you want to drop existing columns then replace mutate with transmute .

If you want to collect variables into columns then:

mtcars %>%
  rownames_to_column("car_names") %>% 
  gather(variable, obs, -car_names)

You could also use interaction . With the example data of @hpesoj626:

college_grad <- c("Graduate", "Non-graduate")
sex <- c("Male", "Female")

df <- expand.grid(college_grad = college_grad, sex = sex)
df$sex_grad <- interaction(df$sex, df$college_grad, sep = ' & ')

The result:

> df
  college_grad    sex              sex_grad
1     Graduate   Male       Male & Graduate
2 Non-graduate   Male   Male & Non-graduate
3     Graduate Female     Female & Graduate
4 Non-graduate Female Female & Non-graduate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM