case_when inserting NAs instead of new assigned values despite all levels are included

Hi,
I have been using case_when without any issue so far.
However, I am having an issue at the moment and can;t figure out if it's a bug or something i am doing wrong, as I receive no error from running the function.

So, I have a dataframe with the following column "Location" with 6 levels:

class(Metadata) # data.frame
class(Metadata$"Catch Location") # factor

levels(Metadata$"Catch Location") 
[1] "1A (Moreton North)"  "A2 (Moreton South)"  "B1 (Cooktown North)" "B2 (Cooktown South)"    "C1 (GOC North)"    "C2 (GOC South)" 

When I try to add a new field (column) called "pop" with mutate and case_when, I get all NAs in the pop column, why?
I use the following code:

Metadata = Metadata %>% mutate(pop = (case_when("Catch Location" == "1A (Moreton North)" ~ "1A_Moreton North",
                                                           "Catch Location" == "A2 (Moreton South)" ~ "A2_Moreton South",
                                                           "Catch Location" == "B1 (Cooktown North)" ~ "B1_Cooktown North",
                                                           "Catch Location" == "B2 (Cooktown South)" ~ "B2_Cooktown South",
                                                           "Catch Location" == "C1 (GOC North)" ~ "C1_GOC North",
                                                           "Catch Location" == "C2 (GOC South)" ~ "C2_GOC South")))

Why is it giving me all NAs in the pop field? I have used the exact same code before withou isssues, so I am not sure what is happening.
I tried with Location as "character" or "factor" and it makes no difference...always same issue...NAs in all pop column.

I would appreciate any feedback and help!
Thanks!
Gabry

Can you give us some some sample data?

A handy way to supply some sample data is the dput() function. In the case of a large dataset something like dput(head(mydata, 100)) should supply the data we need. Just do dput(mydata) where mydata is your data. Copy the output and paste it here between
```

```

Thanks

Hi, the solution was provided by another user in Github:
<you need to put Catch Location on the LHS in backticks not quote marks. i.e.

case_when(`Catch Location` == 

That worked! hope it can help others too!

1 Like

Thanks for getting back to us.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.