887
887

Reputation: 619

Case_when error 'x must be a character vector, not a double vector'?

I am trying to use case_when() to categorize observations based upon a four digit number (which is saved as a character/string variable).

My data is as follows:

Form
2 1 0 1
1 0 1 2
2 2 0 0 
2 1 0 1 

I am using case_when() as follows:

dat <- dat %>%
mutate(FormName = case_when(
(form == '2 1 0 1') ~ 'Open Left', 
(form == '1 0 1 2') ~ 'Open Right', 
(form == '2 2 0 0') ~ 'Spread', 
TRUE ~ 0))

Which should produce:

Form        FormName
2 1 0 1     'Open Left'
1 0 1 2     'Open Right'
2 2 0 0     'Spread'
2 1 0 1     'Open Left'

Instead, I am getting the following error:

Error: Problem with `mutate()` input `FormName`.
x must be a character vector, not a double vector.
ℹ Input `formation` is `case_when(...)`.

I do not understand why this is occurring, as the column 'form' is a character variable? Any idea how I can fix this?

Upvotes: 1

Views: 1112

Answers (2)

Guest
Guest

Reputation: 1

The issue is in the last condition of the case_when statement, TRUE ~ 0. The 0 is a numeric, but the other conditions of the case_when return a character, and R requires all values in a column to be the same data type. You should change that last condition to TRUE ~ '0'.

Upvotes: 0

Onyambu
Onyambu

Reputation: 79328

The best way to go about this:

create a named vector and use the vector

vct = c('2 1 0 1' = "Open Left", '1 0 1 2' = "Open Right", '2 2 0 0' = "Spread")
dat %>%
  mutate(FormName  = vct[form])

Upvotes: 1

Related Questions