rdplyrgreplmutate

dplyr mutate case_when grepl not returning values correctly in R


In the given dataset i have cash , other as well as cash.other at position 7.

df <- data.frame(values = c("loan", "cash", "equity", 
"other", "commercial.news", "money.news", "cash.other"))

I am trying to return grepl("cash.other", tolower(values)) ~ "Cash_Other" but it is returning it as Cash.

In the original dataframe i have cash, other and cash.other as well, which is why i need a to return cash.other as Cash_Other

df <- df %>%
  mutate(values = case_when(
    grepl("loan", tolower(values))  ~ "Lond",
    grepl("cash", tolower(values))  ~ "Cash",
    grepl("equity", tolower(values)) ~ "Equity",
    grepl("other", tolower(values)) ~ "Other",
    grepl("commercial.news", tolower(values)) ~ "Commercial_News",
    grepl("money.news", tolower(values)) ~ "Money_News",
    grepl("cash.other", tolower(values)) ~ "Cash_Other",
    TRUE ~ as.character(values)
  ))

df

How do i return Cash_Other when the case is cash.other?

           values
1            Lond
2            Cash
3          Equity
4           Other
5 Commercial_News
6      Money_News
7            Cash

Solution

  • Not sure if Lond as replacement for loan is a typo, but if you wish to convert to CamelCase, then try the following:

    library(snakecase)
    df <- data.frame(values = c("loan", "cash", "equity", 
                                "other", "commercial.news", "money.news", "cash.other"))
    df$values2 <- snakecase::to_upper_camel_case(df$values, sep_out = "_")
    #            values         values2
    # 1            loan            Loan
    # 2            cash            Cash
    # 3          equity          Equity
    # 4           other           Other
    # 5 commercial.news Commercial_News
    # 6      money.news      Money_News
    # 7      cash.other      Cash_Other