首页 > 解决方案 > rapply“替换”行为不符合预期

问题描述

我正在使用 R 在列表中搜索长度为 0 的子元素,并用向量替换这些子元素。我认为使用此代码rapply会起作用:

temp1 <- list(issn = "", essn = "2042-8812", pubtype = list(), recordstatus = "PubMed", pubstatus = "258")
temp2 <- rapply(temp1, function(x) length(x), classes = "list", how = "replace")
stopifnot(!identical(temp1, temp2))  ## fails as temp1 and temp2 are identical

有趣的是,如果我做(我相信是)完全相同的事情,但在 中使用条件语句lapply,我会得到预期的结果:

temp3 <- lapply(temp1, function(x) if (class(x) == "list") length(x) else x)
stopifnot(!identical(temp1, temp3))  ## succeeds as temp1 and temp2 are not identical

显然,我做错了什么rapply,但我不知道是什么。谢谢。

标签: r

解决方案


?rapply文档(粗体我的)

此功能有两种基本模式。如果'how = "replace"',每个
'object' 的元素,它本身不是类似列表并且有一个类
包含在“类”中被应用“f”的结果替换
元素。

所以rapplywithhow = "replace"不适用于list元素。


推荐阅读