R根据另一列的因子水平创建新的值列 [英] R Create new column of values based on the factor levels of another column

查看:66
本文介绍了R根据另一列的因子水平创建新的值列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据另一列的值创建一个新的值列.如果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).还向不使用apply函数的任何其他解决方案开放.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆