Home > Software engineering >  Conditional mutate by matching strings or characters
Conditional mutate by matching strings or characters

Time:03-24

I want to add a new column like how these tables change below. Where I keep the values 'member' and 'casual' but change 'Subscriber' to 'member' and 'Customer' to 'casual' in a new column. I tried using a conditional mutate but it gives me the error "Error in FUN(left) : invalid argument to unary operator".

If anyone has any ideas on how to get this working, I'd greatly appreciate your input!

member_casual
member
casual
Subscriber
Customer
Subscriber
Customer

Changes to:

member_casual membership_type
member member
casual casual
Subscriber member
Customer casual
Subscriber member
Customer casual
df < - df %>% 
  mutate(membership_type = case_when(member_casual == "member" ~ "member",
                                     member_casual == "casual" ~ "casual",
                                     member_casual == "Subscriber" ~ "member",
                                     member_casual ==  "Customer" ~ "casual"))

>>Error in FUN(left) : invalid argument to unary operator

CodePudding user response:

One possible solution: since you only have two desired categories in your transformation, you could use ifelse().

df < - df %>% 
  mutate(membership_type = ifelse(member_casual %in% c("member", "Subscriber"), "member", "casual"))

The ifelse() function will check the Boolean condition in the first argument. If the first argument is TRUE, ifelse() will return the second argument; otherwise, it will return the third argument.

CodePudding user response:

  1. Your last argument needs a default which you set with TRUE ~ default value

so as it applies to your example, the below should work.

df < - df %>% 
  mutate(membership_type = case_when(member_casual == "casual" ~ "casual",
                                     member_casual == "Subscriber" ~ "member",
                                     member_casual == "Customer" ~ "casual",
                                     TRUE ~ "member"))
  • Related