R根据另一列的因子水平创建新的值列

时间:2020-03-03 05:20:10

标签: r apply

我正在尝试根据另一列的值创建一个新的值列。如果iucnStatus列中的值是“ LC”或“ NT”,我希望新列中(受到威胁)的值是“ Not_Threatened”。如果iucnStatus中的值为“ VU”,“ EN”,“ CR”,“ EW”或“ EX”,则我希望新列(受威胁的)中的值为“威胁”。在编写代码以创建新列方面,我走了这么远:

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

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

但是我不确定要将哪个函数传递给function(x)。还向不使用apply函数的任何其他解决方案开放。

1 个答案:

答案 0 :(得分:0)

如果您只有两种状态,则可以使用ifelse

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

如果还要检查更多状态码,则可以使用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
         ))