我正在使用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
上做错了,但我不知道该怎么办。谢谢。
答案 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.
因此rapply
与how = "replace"
不能在list
元素上使用。