string 检查变量是否具有值 ''

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17654913/
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-09 02:01:30  来源:igfitidea点击:

Check if variable has the value ''

rstring

提问by rdatasculptor

In a script I try to get running sometimes are variables being filled with ''(wich means: completely empty), e.g.

在我尝试运行的脚本中,有时会填充变量''(这意味着:完全空),例如

variable <- ''

Does anyone know of a method to check if variable has the value ''?

有谁知道检查变量是否具有值的方法''

is.null(variable)doesn't seem to work. ''is not the same as NULL.

is.null(variable)似乎不起作用。''不一样NULL

回答by Konrad Rudolph

''is an empty character. It does notmean “completely empty” –?that is indeed NULL.

''是一个空字符。它意味着“完全排空?” -这确实是NULL

To test for it, just check for equality:

要测试它,只需检查是否相等:

if (variable == '') …

If you want to check whether a variable exists, you need to use …?exists:

如果要检查变量是否存在,则需要使用 ...? exists

if (exists('variable')) …

But in fact there are very few use-cases for existsin normal code, since as the author of the code you should knowwhich variables exist and which don't. Rather, it's primarily useful in library functions.

但实际上,exists在普通代码中很少有用例,因为作为代码的作者,您应该知道哪些变量存在,哪些不存在。相反,它主要用于库函数。

However, the error you're getting,

然而,你得到的错误,

missing value where TRUE/FALSE needed

需要 TRUE/FALSE 的缺失值

does notmean that the variable doesn't exist. Rather, ifcannot deal with missing values –?i.e. NA. An NAoccurs as a result of many computations which themselves contain an NAvalue. For instance, comparing NAto any value (even NAitself) again yields NA:

意味着变量不存在。相反,if无法处理缺失值 –?ie NA。AnNA是许多计算的结果,这些计算本身包含一个NA值。例如,与NA任何值(甚至NA它本身)进行比较再次产生NA

variable = NA
variable == NA
# [1] NA

Since ifexpects TRUEor FALSE, it cannot deal with NA. If there's a chance that your values can be NA, you need to check for this explicitly:

由于if期望TRUEor FALSE,它无法处理NA。如果您的值有可能是NA,您需要明确检查这一点:

if (is.na(variable) || variable == '') …

However, it's normally a better idea to exclude NAvalues from your data from the get-go, so that they shouldn't propagate into a situation like the above.

但是,NA从一开始就从数据中排除值通常是一个更好的主意,这样它们就不会传播到上述情况中。

回答by bartektartanus

In stringipackage there is function for this.

stringi包中有这个功能。

require(stringi)    
stri_isempty(c("A","")) 

You can also install this package from github: https://github.com/Rexamine/stringi

你也可以从 github 安装这个包:https: //github.com/Rexamine/stringi

回答by Balthasar

If you wish to both check and replace these values with NAs all at once, as is usually the case, just use dplyr::na_if():

如果您希望同时检查这些值并将其替换为NAs ,通常情况下,只需使用dplyr::na_if()

variable <- ''
dplyr::na_if(variable, "")
#> [1] NA