[英]Robust test if an expression can be coerced to character to avoid as.character error
I am looking for a reliable test (= does not throw an error) whether an expression can be converted to character.我正在寻找一个可靠的测试(= 不会引发错误)表达式是否可以转换为字符。
How could I do this?我怎么能这样做?
I want to avoid that calling as.character
throws an error like eg.我想避免调用
as.character
会引发错误,例如。 in case of as.character(function() 1)
which says:在
as.character(function() 1)
的情况下:
Error in as.character(function() 1) :
cannot coerce type 'closure' to vector of type 'character'
Example expressions:示例表达式:
# do not throw an error in as.character
1
1:10
"test"
NA
1 + 2
# do throw an error in as.character
function() 1
new.env()
PS: Of course I could use tryCatch
but is there an easier way? PS:当然我可以使用
tryCatch
但有更简单的方法吗?
Edit 1: I want to test if the result value of an expression can be coerced to a character (not the expression itself)编辑1:我想测试一个表达式的结果值是否可以强制转换为一个字符(而不是表达式本身)
I'm sure there will be better answers to this question and I look forward to reading them.我相信这个问题会有更好的答案,我期待着阅读它们。 Wanting evaluated results assumes they are prone to evaluation, but if any unknown input is accepted, one can't be sure.
想要评估结果假定它们易于评估,但如果接受任何未知输入,则无法确定。
Depending upon where your pipeline is going next, explore variants of quote
or expression
.根据您的管道接下来的发展方向,探索
quote
或expression
的变体。
as.character(quote(function() 1))
[1] "function" "NULL"
[3] "1" "c(1, 20, 1, 31, 20, 31, 1, 1)"
as.character(expression(1 + 2))
[1] "1 + 2"
as.character(eval(expression(1+2)) # works in this case
[1] "3"
as.character(eval(expression(1+2, 'A') # what would this be?
[1] "A" # so nonsense
Another approach might be to find out what sort of thing in the wild you're being passed and then decide what to do with it:另一种方法可能是找出你正在通过的野外是什么样的东西,然后决定如何处理它:
as.character(typeof(function() 1))
[1] "closure" # not safe or just pass along "closure" and move on
as.character(typeof(new.env())
[1] "environment" # not safe
as.character(typeof(expression(1+2))
[1] "expression" # safe (maybe) for further manipulation, replace typeof with eval
But typeof
isn't immune to other user errors on the way to evaluated results但是
typeof
在评估结果的过程中不能避免其他用户错误
as.character(typeof(function(x) 1, 'a'))
Error in typeof(function(x) 1, "a") : unused argument ("a")
I find this an interesting question because I've always assumed there was a way to render to string any object in R, though the path may be convoluted.我发现这是一个有趣的问题,因为我一直认为有一种方法可以渲染到 R 中的任何 object,尽管路径可能很复杂。
You'll know best regards your full project and where you are trying to control evaluation.您将最了解您的整个项目以及您试图控制评估的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.