STAT545-UBC / Discussion

Public discussion
37 stars 20 forks source link

Changing the content in one cell of a factor, based on that cell's current content #522

Closed MielleM closed 5 years ago

MielleM commented 5 years ago

I am trying to rename a variable in the "region" (renamed from country) column from "United States" to "USA" so I can join it to something. Seems like this should be simpler so I'm probably missing something basic!

This is what I have:

region year lifeExp
United States 2007 78.242

This is what I want:

region year lifeExp
USA 2007 78.242

I've tried this ("Evaluation error: false must be type character, not integer") but it seems like the fact that the "region" column is a factor is causing issues. gapminder %>% filter(year == 2007) %>% filter(country %in% c("Canada", "United States", "Mexico")) %>% rename(region = "country") %>% mutate(region = if_else(region == "United States", "USA", region))

Which is based on the following code from in class: gapminder %>% mutate(lifeExp = if_else(country == "Canada" & year == 1952, 70, lifeExp)) %>% filter(country == "Canada")

I've also tried using recode() which potentially seems to have some tibble incompatibility.

I know it's just one value, but I'd like to find a way to do this as cleanly as possible so I can use it for something more complex in the future. Thanks!

ChadFibke commented 5 years ago

Hey @MielleM Try:

gapminder %>% 
  filter( year  == 2007 ) %>%
  filter( country %in% c( "Canada", "United States", "Mexico" ) ) %>%
  rename( region  = country ) %>% 
  mutate( region = as.character( region ) ) %>% 
  mutate( region = ifelse( region == "United States", "USA", region ) )

Originally country is a factor, which is read by the user as a string of characters, but under the hood they are actually integers! So your if else statement was saying if TRUE replace with a character string, if FALSE keep as the under-the-hood-integer. Since these are different types R complains! Hope this helps.

Chad

MielleM commented 5 years ago

Hi @ChadFibke, this worked! Thank you!

Appreciate the background knowledge as well.