9
votes

The Titanic Dataset can be downloaded from kaggle: kaggle.com/c/titanic/data. Please use the train.csv or install the package 'titanic' and use the dataset titanic_train.

This works

library(dplyr)
library(stringr)

titanic <- titanic %>%
    mutate(Cabin_Letter = ifelse(!is.na(Cabin), str_extract(Cabin, "[A-Z]+"), 'Unknown'))

This does not work entirely

titanic <- titanic %>%
    mutate(Cabin_Letter = factor(ifelse(!is.na(Cabin), str_extract(Cabin, "[A-Z]+"), 'Unknown')))

Warning:

Warning messages: 1: In mutate_impl(.data, dots) : Unequal factor levels: coercing to character 2: In mutate_impl(.data, dots) : binding character and factor vector, coercing into character vector 3: In mutate_impl(.data, dots) : binding character and factor vector, coercing into character vector 4: In mutate_impl(.data, dots) : binding character and factor vector, coercing into character vector 5: In mutate_impl(.data, dots) : binding character and factor vector, coercing into character vector 6: In mutate_impl(.data, dots) : binding character and factor vector, coercing into character vector 7: In mutate_impl(.data, dots) : binding character and factor vector, coercing into character vector

How could I resolve this issue? I don't want to take the extra line:

titanic$Cabin_letter <- factor(titanic$Cabin_letter)
1
I could not find the titanic data frame in R. Please clarify how did you get this data if possible. - www
oh sorry, you can use the package 'titanic' or download from kaggle: kaggle.com/c/titanic/data - cappuccino
There are four datasets from the titanic R package. None of them called titanic. Could you make your example code reproducible by providing more information about the data? - www
I ran your code, use titanic_train as titanic, but I could not reproduce your warning message. The code seems to work fine. - www
@ycw I restarted my computer and R and you are right, I no longer get an error! Next time I will try this first before posting. Weird. Any idea why such simple fix does the trick or why such an error arises? - cappuccino

1 Answers

28
votes

This issue can happen if the data is grouped (grouped_df) using the group_by() function. I just ran into it. My solution was to ungroup() the data frame and then convert to factor using as.factor().