首页 > 解决方案 > 如何检查数据框中的列中是否有某些字符用于 if 语句?

问题描述

我有一个数据框,我想将该数据框的特定列的任何行中是否存在某个值作为逻辑条件。

此列中的每个值都是一个字符。以下是我在本专栏中拥有的一些数据示例:

示例第 1 行:

ID=AB3,totalServicePrice=25.0,isLeased=true,错误=错误 [errorId=[CSSM-SOR-306],errorMessage=未知错误。]

示例第 2 行:

ID=AB4,totalServicePrice=25.0,isLeased=true,error=null

如果该列在任何行中包含 error=Error,我希望我的 if 子句执行,如果没有,我希望我的 else 子句执行。我尝试了以下事情:

if('error=Error' %in% equipmentSubstring3$object.object)

if(equipmentSubstring3$object.object %like% 'error=Error')

if(grepl('error=Error', equipmentSubstring3$object.object)

if(grepl('error=Error', equipmentSubstring3$object.object, fixed=TRUE)

第一个 if 子句的计算结果为 false。第 2 到第 4 也都评估为 false,因为我放在 if 子句中的每个条件都会为列中的每一行返回一个 true 和 false 列表,并且 if 语句只评估该列表中的第一个元素。

如果我的列包含我要查找的值,如何使 if 子句评估为 true?

标签: r

解决方案


让我看看我是否理解,如果列错误在他的至少一个行中包含“错误”一词,那么您想要运行一个子句(条件评估为真)。这将是我的解决方案:

    library(stringr) # Useful for string manipulation
    findingError <- str_detect(pattern = "Error", dataframe$errorcolumn) # This function detects the presence of a pattern within a string

    if(any(findingError)) { #The Any function evaluates to true when at least one of the components of a logical vector is TRUE
    # Do something
    }

推荐阅读