r - 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
,但我不知道是什么。谢谢。
解决方案
从?rapply
文档(粗体我的)
此功能有两种基本模式。如果'how = "replace"',每个 'object' 的元素,它本身不是类似列表并且有一个类 包含在“类”中被应用“f”的结果替换 元素。
所以rapply
withhow = "replace"
不适用于list
元素。
推荐阅读
- c - 对文件内容使用 atoi() 时出现意外结果,逐字符读取
- angular5 - 在使用 Angular 5(5.2.11) 设置 webpack 4(4.14.0) 时,在控制台上出现运行时错误
- c++ - 使用 for 循环将数据输入数组
- excel - 使用带有运算符和的字符串数组过滤数据
- excel - 将一个 excel 文件中的值用于另一个 excel 文件的图表
- html - 带有 svg 的对象标签填充了整个网页
- mysql - 使用 SSHTunnelForwarder 连接远程 MYSQL 数据库时出现连接错误
- excel - 在 VBA 代码中压缩多个 OR 条件
- c - 父代码在 C 中的多进程程序中被调用两次
- php - 尝试更新数组时出现错误