R 根据另一列的因子水平创建新的值列 [英] R Create new column of values based on the factor levels of another column
问题描述
我正在尝试根据另一列的值创建一个新的值列.如果 iucnStatus 列中的值是LC"或NT",我希望新列(受威胁)中的值是Not_Threatened".如果 iucnStatus 中的值是VU"、EN"、CR"、EW"或EX",我希望新列(受威胁)中的值是受威胁".我在编写创建新列的代码方面做到了这一点:
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)
但我不确定要传递给 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.
推荐答案
如果你只有两种状态,你可以使用 ifelse
.
You can use ifelse
if 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)]
如果还有很多状态码要检查,可以使用case_when
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
))
这篇关于R 根据另一列的因子水平创建新的值列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!