10

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)
5
  • I could not find the titanic data frame in R. Please clarify how did you get this data if possible.
    – www
    Aug 30, 2017 at 14:09
  • oh sorry, you can use the package 'titanic' or download from kaggle: kaggle.com/c/titanic/data
    – cappuccino
    Aug 30, 2017 at 14:23
  • 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
    Aug 30, 2017 at 14:41
  • I ran your code, use titanic_train as titanic, but I could not reproduce your warning message. The code seems to work fine.
    – www
    Aug 31, 2017 at 17:14
  • @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
    Sep 5, 2017 at 15:36

1 Answer 1

29

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().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.