Reabo
Reabo

Reputation: 87

How to create new variable from two existing categorical variables in R

I have two different category variables: A=factor(c(1,2,1,2,1)) and B=factor(c("g","g","h","g","h")). I want to have a new categorical variable based on these two categories. For example I want to call (1,g)=K, (2,g)=J, (1,h)=L. So the new variable will be factor(c("K","J","L","J","L")).

Upvotes: 1

Views: 1265

Answers (2)

Gauri
Gauri

Reputation: 1

df$Cross_Tab <- dplyr::case_when(
  df$A %in% c ("1") & 
    df$B %in% c ("g") ~ K,
  df$A %in% c ("2") & 
    df$B %in% c ("g") ~ J,
  df$A %in% c ("1") & 
    df$B %in% c ("h") ~ L,
  )  

Upvotes: 0

jkd
jkd

Reputation: 1654

You could use a named vector to achieve this:

A <- factor(c(1, 2, 1, 2, 1))
B <- factor(c("g", "g", "h", "g", "h"))

conv <- c("1 g" = "K",
          "2 g" = "J",
          "1 h" = "L")

C <- conv[paste(A, B)]

Upvotes: 1

Related Questions