Home > database >  Assigning new column values based on other columns
Assigning new column values based on other columns

Time:11-16

Im trying to create a new column in my dataset based on other countries within the data but having some issues getting the code right. If anyone minds taking a quick look at this and pointing me in the right direction that would be great.

I have created the countries that i need split to save writing it out below

east_countries = c("Albania", "Bosnia and Herzegovina", "Croatia", "Cyprus", "Egypt, Arab Rep.",  "Greece", "Israel", "Lebanon", "Libya",
                              "Montenegro", "Slovenia", "Syrian Arab Republic", "Turkiye")
west_countries = c("Algeria", "France", "Italy", "Malta", "Morocco", "Spain", "Tunisia") 

if(fisheries_df$Country_Name %in% east_countries){
  fisheries_df$basin = "east"
} 
if(fisheries_df$Country_Name %in% west_countries){
  fisheries_df$basin = "west"
} 

I though the above would work but maybe im missing the positions within the IF statement. I also tried something like below but again had no luck. No fussy which method is use there

data snipet

Country_Name year   fisheries_production 
Albania      1997                1111.    
France      1997                 2808.     
Greece      1997                 3058.     

fisheries_df[which(fisheries_df$Country_Name %in% west_countries),]=fisheries_df$basin="west"

CodePudding user response:

You can use dplyr::case_when:

fisheries_df$basin <- dplyr::case_when(
  fisheries_df$Country_Name %in% east_countries ~ "east",
  fisheries_df$Country_Name %in% west_countries ~ "west",
  TRUE ~ NA_character_
)
  •  Tags:  
  • r
  • Related