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
Check if variable has the value ''
提问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 exists
in 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, if
cannot deal with missing values –?i.e. NA
. An NA
occurs as a result of many computations which themselves contain an NA
value. For instance, comparing NA
to any value (even NA
itself) again yields NA
:
不不意味着变量不存在。相反,if
无法处理缺失值 –?ie NA
。AnNA
是许多计算的结果,这些计算本身包含一个NA
值。例如,与NA
任何值(甚至NA
它本身)进行比较再次产生NA
:
variable = NA
variable == NA
# [1] NA
Since if
expects TRUE
or 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
期望TRUE
or FALSE
,它无法处理NA
。如果您的值有可能是NA
,您需要明确检查这一点:
if (is.na(variable) || variable == '') …
However, it's normally a better idea to exclude NA
values from your data from the get-go, so that they shouldn't propagate into a situation like the above.
但是,NA
从一开始就从数据中排除值通常是一个更好的主意,这样它们就不会传播到上述情况中。
回答by bartektartanus
In stringi
package 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 NA
s all at once, as is usually the case, just use dplyr::na_if()
:
如果您希望同时检查这些值并将其替换为NA
s ,通常情况下,只需使用dplyr::na_if()
:
variable <- ''
dplyr::na_if(variable, "")
#> [1] NA