string 比较字符串与 R 中的逻辑运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31948808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:26:14  来源:igfitidea点击:

Compare strings with logical operator in R

rstringfunctioncomparelogical-operators

提问by Rich Bridgwater

I'm getting an error trying to compare and set weekday string values as either a "weekend" or a "weekday" using R. Any suggestions on how to approach this problem in a better way would be great.

我在尝试使用 R 将工作日字符串值比较和设置为“周末”或“工作日”时遇到错误。有关如何以更好的方式解决此问题的任何建议都会很棒。

x <- c("Mon","Tue","Wed","Thu","Fri","Sat","Sun")

setDay <- function(day){
          if(day == "Sat" | "Sun"){
           return("Weekend")
          } else { 
            return("Weekday")
          }
        }

sapply(x, setDay)

This is the error I get back in RStudio:

这是我在 RStudio 中返回的错误:

Error in day == "Sat" | "Sun" : 
  operations are possible only for numeric, logical or complex types

回答by josliber

Instead of using sapplyto loop through each individual day in xand check whether it's the weekday or weekend, you can do this in a single vectorized operation with ifelseand %in%:

您可以使用和在单个向量化操作中执行此操作,而不是使用sapply循环遍历每一天x并检查它是工作日还是周末:ifelse%in%

ifelse(x %in% c("Sat", "Sun"), "Weekend", "Weekday")
# [1] "Weekday" "Weekday" "Weekday" "Weekday" "Weekday" "Weekend" "Weekend"

The motivation for using vectorized operations here is twofold -- it will save you typing and it will make your code more efficient.

在这里使用矢量化操作的动机是双重的——它可以节省您的打字时间,并使您的代码更有效率。