1

I'm trying to add a new column with the values "N"; "NE"; "CO"; "S" and "SE based on the values of the Group.2 column, say (AL, CE, BA = NE).

Tried using mutate with case_when and it didn't work

esc_c  %>%
  mutate(
    reg_uf = case_when(
      Group.2 == "GO" | "CO",
      Group.2 == "TO" |"CO",
      Group.2 == "DF" |"CO",
      Group.2 == "MT" |"CO",
      Group.2 == "MS" |"CO", TRUE ~ Group.2))

would apreciate an answer using dplyr

roup.1 Group Group.2 Group.3 CO_UF_END TP_ESCOLARIDADE Cod_IBGE uf_sigla uf_des
1 12 AC Acre 12 3.921569 1200417 NA NA
2 27 AL Alagoas 27 3.783784 2704233 NA NA
3 16 AP Amapá 16 3.815789 1600393 NA NA
4 13 AM Amazonas 13 3.937500 1302661 NA NA
5 29 BA Bahia 29 3.726444 2916394 NA NA
6 23 CE Ceará 23 3.886076 2307054 NA NA
7 53 DF Distrito Federal 53 3.957739 5300108 NA NA
8 32 ES Espírito Santo 32 3.905660 3203381 NA NA
9 52 GO Goiás 52 3.897945 5210048 NA NA
1
  • 2
    I think the | would be ~ i.e. Group.2 == "GO" | "CO" would be Group.2 == "GO" ~ "CO" Commented Dec 8, 2020 at 21:17

1 Answer 1

2

We don't need the multiple == and returning the same 'CO', instead, can place together in a single vector and then use %in%

library(dplyr)
esc_c1 <- esc_c  %>%
   mutate(
      reg_uf = case_when(
           Group.2 %in% c( "GO", "TO", "DF", "MT", "MS") ~ "CO",
           TRUE ~ Group.2))

NOTE: The syntax for case_when is logical_expression ~ value and not logical_expression | value

Sign up to request clarification or add additional context in comments.

2 Comments

I guess this case_when could become an ifelse now.
Thanks for the answer! This worked perfectly, thanks a bunch!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.