0

I have a dataframe of countries and connected data, but the countries are only listed by integer codes. I want to create a new variable for the country name and have a function change a given row's country name to the appropriate one.

I can easily do this for any given country with the following code:

for (i in 1:nrow(mena)){
  if (mena$ccode[i] == 600){
    mena$cname[i] <- "Morocco"}

However, when I try to make a function that takes country name and country code as its argument, my code doesn't result in an error message, but doesn't affect my dataframe at all. Here is the function I wrote:

assignGWName <- function(countryname, countrycode){
  for (i in 1:nrow(mena)){
    if (mena$ccode[i] == countrycode){
      mena$cname[i] <- countryname}
  }
}

If I call

assignGWName("Morocco", 600)

I get no effect. Why?

  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Note that assignments that happen inside a function only affect values inside that function. It does not change the value of global variables -- it creates a new local copy. – MrFlick Jul 14 '20 at 04:16
  • I have a dataframe with, among other variables, country code(ccode) taken from a published dataset, and country name(cname) which is not included in the original dataset. The sample input each time I call the assignGWName function would be a name and three digit code. The desired output each time I use this function would be for each row in the dataframe with that country code to have that name in the cname column. – citizen Jul 14 '20 at 04:22
  • It sounds like it would be better just to create a table of all your code-country name values and then just `merge()` that in all at once. Doing a loop like that for each value would be quite inefficient. – MrFlick Jul 14 '20 at 04:26
  • try using the `countrycode` package... probably does what you're trying to do efficiently. If you're curious, you can see how it works here https://github.com/vincentarelbundock/countrycode – CJ Yetman Aug 04 '20 at 19:21

0 Answers0