强行“替换”行为不符合预期

时间:2019-12-10 21:19:36

标签: r

我正在使用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上做错了,但我不知道该怎么办。谢谢。

1 个答案:

答案 0 :(得分:1)

摘自?rapply文档(黑体字)

This function has two basic modes.  If ‘how = "replace"’, each
element of ‘object’ which is not itself list-like and has a class
included in ‘classes’ is replaced by the result of applying ‘f’ to
the element.

因此rapplyhow = "replace"不能在list元素上使用。