2

I have a question very similar to this question

 country                      continent
   <chr>                        <chr>    
 1 Taiwan                       Asia     
 2 New Zealand                  Oceania  
 3 Bulgaria                     Europe   
 4 Bahamas                      Americas 
 5 Serbia                       Europe   
 6 Tajikistan                   Asia     
 7 Southern Sub-Saharan Africa  NA       
 8 Cameroon                     Africa   
 9 Indonesia                    Asia     
10 Democratic Republic of Congo Africa  

How do I use a function/write a loop so that when the country is "Bahamas" that it converts the continent so that it now says South America?

The page that I linked was the closest answer I could find but it differed from my question because I am trying to manipulate one column based on the values in a different column.

I tried using ifelse() but that did not work:

gm %>%
  ifelse(country == "Bahamas", continent == "S America", continent)

Any insight would be greatly appreciated!

2 Answers2

3

You need to mutate:

library(dplyr)
gm %>%
  mutate(continent = ifelse(country == "Bahamas", "S America", continent))
neilfws
  • 32,751
  • 5
  • 50
  • 63
1

This works:

gm[,'continent'][gm[,'country'] == "Bahamas"] <- "South America"

You might get a warning message like this if "South America" is not already in the dataframe:

Warning message:
In `[<-.factor`(`*tmp*`, gm[, "country"] == "Bahamas", value = c(2L,  :
  invalid factor level, NA generated

This means you need to add the level first, you are trying to issue a level which doesn't exist:

levels(gm$continent) <- c(levels(gm$continent), "South America")
gm[,'continent'][gm[,'country'] == "Bahamas"] <- "South America"

(run time on this approach [5M entries in a dataframe, 10 repeated measures] was 4x faster than the dplyr method)

rg255
  • 4,119
  • 3
  • 22
  • 40
  • 1
    I find that learning how to solve problems without using _tidyverse_ packages helps me learn a lot more about how R works. Thank you! – ChinookJargon Apr 18 '18 at 15:48
  • I should spend some time familiarising myself with tidyverse - it's very fashionable at the moment - but sometimes feels like people assume it's better than any other option, in my experience it's situation dependent and other approaches can often out perform tidyverse. – rg255 Apr 18 '18 at 19:44
  • I totally agree with you. Since I am a noob, initially focusing on the Tidyverse gives me a set of tools that would be more difficult to learn with Base R functionality. – ChinookJargon Apr 18 '18 at 22:03