0

I am trying to create a new column of values based on the values of another column. If the values in column iucnStatus are "LC" or "NT" I want the value in the new column (threatened) to be "Not_Threatened". If the values in iucnStatus are "VU", "EN", "CR", "EW", or "EX" I want the value in the new column (threatened) to be "Threatened." I got this far in writing code to create the new column:

df<-read.csv('master2.csv')

df$threatened <-apply(df$iucnStatus, 1,function(x)

But I wasn't sure what function to pass into function(x). Also open to any other solutions that don't use the apply function.

Cyph
  • 71
  • 5

1 Answers1

0

You can use ifelseif you have only two types of status.

df$Threatened <- ifelse(df$iucnStatus %in% c("LC","NT"),"Not_Threatened", "Threatened")
#Without `ifelse`
#df$Threatened <- c("Threatened", "Not_Threatened")[(df$iucnStatus %in% c("LC","NT")+ 1)]

If there are many more status codes that you want to check, you can use case_when

library(dplyr)

df %>%
  mutate(Threatened = case_when(
                        Status %in% c("LC","NT") ~ "Not_Threatened", 
                        Status %in% c("VU", "EN", "CR", "EW","EX") ~ "Threatened", 
                        #More conditions
         ))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213