从R列表中的所有嵌入式列表中删除元素 [英] deleting an element from all embedded lists in a list in R

查看:157
本文介绍了从R列表中的所有嵌入式列表中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表(g),如下所示.要从其中一个嵌入列表(例如第一个列表)中删除元素k,我可以做:g[[1]]$k <- NULL.

I have a list (g) of lists as shown below. To delete element k from one of the embedded lists (ex. 1st list), I can do: g[[1]]$k <- NULL.

但是当我尝试从所有嵌入列表中删除元素k时,我的lapply代码失败了吗?是否有Base R修复程序?

But when I try to delete element k from all embedded lists, my lapply code fails? Is there a Base R fix?

g <- list(b1 = list(data.frame(a = 1:3), k = 4:6), b2 = list(data.frame(a = 8:9), k = 7:9))

lapply(1:length(g), function(i) g[[i]]$k <- NULL) ## FAILS to delete `k` from all embedded lists

推荐答案

R是一种功能语言,因此传递的是参数的副本,而不是指向它们的指针.函数不应在参数的原始"上进行修改.因此,您不应假定对该函数内部访问的值的修改在该函数的环境之外将是可见的",除非存在对原始名称(或此处进行的替代名称)的赋值,除非 :

R is a functional language and as such copies of arguments are passed rather than pointers to them. Functions are not supposed to make modifications on the "originals" of the arguments. So you should not assume that modifications to values accessed inside function will be "visible" outside that function's environment unless there is an assignment back to the original name (or to an alternate name such as is done here):

> g2 <- lapply(g, function(i){ i$k <- NULL; i})
> g2
$b1
$b1[[1]]
  a
1 1
2 2
3 3


$b2
$b2[[1]]
  a
1 8
2 9

还请注意:在将"k"值归零后,需要返回修改后的元素.似乎更直接地传递实际元素而不是使用索引. <-<<-函数所允许的不修改参数"规则有一个隐含例外.

Note also: the need to return the modified element after the "k" value is nulled out. Seemed more direct to pass the actual elements rather than using an index. There is an implicit exception to the rule of "no modifying of arguments" allowed to the <- and <<- functions.

这篇关于从R列表中的所有嵌入式列表中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆