如何使 rjson 的 fromJSON 方法将 JSON NULL 转换为 R NA?
我当然可以在 R 中解决这个下游问题,但我认为这比只让 rjson 以某种方式为我做这件事会更混乱。能做到吗?
I could of course solve this downstream in R, but I think that would be messier compared to just get rjson to do it for me somehow. Can it be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两个想法:
RJSONIO
,并使用它的fromJSON
。要查找的参数是nullValue
,您可以将其设置为 NA。很久以前,在做了一些速度测试之后,我从 rjson 切换到了 RJSONIO,它还生成了更具可读性的 JSON。gsub()
将“null”替换为“NA”。如果您不熟悉正则表达式,这并不是特别可靠(如果“null”是一些文本的一部分,您最终可能会删除它,因此务必小心)。Two ideas:
RJSONIO
instead, and use itsfromJSON
. The argument to look for isnullValue
, which you can set to be NA. I switched from rjson to RJSONIO a long time ago, after doing some speed tests and it also produces somewhat more readable JSON.gsub()
. This isn't particularly robust if you aren't familiar with regular expressions (if "null" is part of a bit of text, you could end up dropping it, so it's important to be careful).在我看来,rjson 包中的
fromJSON
的所有工作都是在 C 代码中完成的,所以我的猜测是,没有一种简单的方法可以在不改变其行为的情况下改变其行为C 代码本身。您最好在 R 中进行转换。您可以简单地将
fromJSON
包装在您自己的函数中,将NULL
替换为NA
。这将防止你的代码本身变得过于混乱。It looks to me like
fromJSON
in the rjson package does all its work in C code, so my guess is that there isn't an easy way to alter its behavior without altering the C code itself. You're probably better off doing the conversion in R.You could simply wrap
fromJSON
in your own function that replacesNULL
toNA
. That would prevent your code itself from getting too terribly messy.