KaC
KaC

Reputation: 287

Add the names of levels in one variable to names of levels in another variable

Is there an easy way to add the names of levels in one variable to names of levels in another variable?

To illustrate, consider the following dataframe:

DF1  <- data.frame(Gender = factor(c("Male", "Female", "Female", "Female", "Male", "Male")),
                   Wealth=factor(c("Rich", "Poor", "Rich", "Poor", "Rich", "Poor")),
                   Education=factor(c("College", "College", "HS", "College", "HS", "HS")))

I would like to add the genders from the Gender variable to the names of levels in the other two variables, like so:

DF2 <- data.frame(Gender = factor(c("Male", "Female", "Female", "Female", "Male", "Male")),
                 Wealth=factor(c("MALE: Rich", "FEMALE: Poor", "FEMALE: Rich", "FEMALE: Poor", "MALE: Rich", "MALE: Poor")),
                 Education=factor(c("MALE: College", "FEMALE: College", "FEMALE: HS", "FEMALE: College", "MALE: HS", "MALE: HS")))

How can it be done?

Upvotes: 0

Views: 71

Answers (1)

Calum You
Calum You

Reputation: 15072

Here's a tidyverse approach that makes it easy to specify a function to be applied to a selection of columns. Note that in many cases factors are amenable to string manipulations. Here we change the case with str_to_upper, concatenate the columns with str_c, and convert back to factor.

DF1 <- data.frame(
  Gender = factor(c("Male", "Female", "Female", "Female", "Male", "Male")),
  Wealth = factor(c("Rich", "Poor", "Rich", "Poor", "Rich", "Poor")),
  Education = factor(c("College", "College", "HS", "College", "HS", "HS"))
)

library(tidyverse)
DF2 <- DF1 %>%
  mutate_at(
    vars(Wealth, Education),
    funs(factor(str_c(str_to_upper(Gender), ": ", .)))
    )
DF2 %>% as_tibble()
#> # A tibble: 6 x 3
#>   Gender Wealth       Education      
#>   <fct>  <fct>        <fct>          
#> 1 Male   MALE: Rich   MALE: College  
#> 2 Female FEMALE: Poor FEMALE: College
#> 3 Female FEMALE: Rich FEMALE: HS     
#> 4 Female FEMALE: Poor FEMALE: College
#> 5 Male   MALE: Rich   MALE: HS       
#> 6 Male   MALE: Poor   MALE: HS

Created on 2018-06-20 by the reprex package (v0.2.0).

Upvotes: 2

Related Questions