rapply“;替换“;行为不符合预期

rapply“;替换“;行为不符合预期,r,R,我使用R搜索长度为0的子元素列表,并用向量替换这些子元素。我认为使用rappy的代码可以工作: temp1 <- list(issn = "", essn = "2042-8812", pubtype = list(), recordstatus = "PubMed", pubstatus = "258") temp2 <- rapply(temp1, function(x) length(x), classes = "list", how = "replace") stopifno

我使用R搜索长度为0的子元素列表,并用向量替换这些子元素。我认为使用
rappy
的代码可以工作:

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

很明显,我的rappy有问题,但我不知道是什么。谢谢。

来自
?rappy
文档(粗体)

此功能有两种基本模式。如果“how=”替换“,则每个 “object”的元素,该元素本身与列表不同,并且具有类 “类”中包含的内容将替换为应用“f”的结果 元素。
因此,使用
how=“replace”
rappy
list
元素上不起作用。

我不知道为什么要在这里使用
rappy
;没有什么可以递归的,而
lappy
就足够了。但也许这只是一个简单的例子。此外,
?rapply
声明“[i]f'how=“replace””,每个本身与列表不同且包含在“classes”中的类的“object”元素将被应用于元素的“f”的结果所替换。”(粗体)。如果我正确地解释了这一点,那么函数只能应用于非
list
类对象,因此
classes=“list”
没有意义;真实数据具有多层嵌套列表。但我认为“这不是列表本身的样子”是关键。谢谢您的关注。@MauritsEvers,如果您的评论是我的回答,我将接受。当然&done;-)
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
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.