R Create new column of values based on the factor levels of another column [duplicate]

倾然丶 夕夏残阳落幕 提交于 2021-01-29 17:14:53

问题


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.


回答1:


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
         ))


来源:https://stackoverflow.com/questions/60500541/r-create-new-column-of-values-based-on-the-factor-levels-of-another-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!