将NULL分配给R中的列表元素? [英] Assigning NULL to a list element in R?
问题描述
我发现这种行为很奇怪,希望更多有经验的用户分享他们的想法和解决方法. 在R中运行以下代码示例:
I found this behaviour odd and wanted more experienced users to share their thoughts and workarounds. On running the code sample below in R:
sampleList <- list()
d<- data.frame(x1 = letters[1:10], x2 = 1:10, stringsAsFactors = FALSE)
for(i in 1:nrow(d)) {
sampleList[[i]] <- d$x1[i]
}
print(sampleList[[1]])
#[1] "a"
print(sampleList[[2]])
#[1] "b"
print(sampleList[[3]])
#[1] "c"
print(length(sampleList))
#[1] 10
sampleList[[2]] <- NULL
print(length(sampleList))
#[1] 9
print(sampleList[[2]])
#[1] "c"
print(sampleList[[3]])
#[1] "d"
列表元素上移. 也许这是预期的,但是我正在尝试实现一个功能,在该功能中我合并列表的两个元素并删除其中的一个.我基本上想丢失该列表索引或将其设置为NULL.
The list elements get shifted up. Maybe this is as expected, but I am trying to implement a function where I merge two elements of a list and drop one. I basically want to lose that list index or have it as NULL.
有什么办法可以给它分配NULL而看不到上述行为吗?
Is there any way I can assign NULL to it and not see the above behaviour?
谢谢您的建议.
推荐答案
好问题.
查看 R-FAQ :
在R中,如果x是一个列表,则x [i]<-NULL和x [[i]]<-NULL从x中删除指定的元素.其中第一个与S不兼容,后者是空操作. (请注意,您可以使用x [i]<-list(NULL)将元素设置为NULL.)
In R, if x is a list, then x[i] <- NULL and x[[i]] <- NULL remove the specified elements from x. The first of these is incompatible with S, where it is a no-op. (Note that you can set elements to NULL using x[i] <- list(NULL).)
考虑以下示例:
> t <- list(1,2,3,4)
> t[[3]] <- NULL # removing 3'd element (with following shifting)
> t[2] <- list(NULL) # setting 2'd element to NULL.
> t
[[1]]
[2] 1
[[2]]
NULL
[[3]]
[3] 4
更新:
正如 The Inferno 的作者所评论的那样,在交易时可能会有更微妙的情况与NULL.考虑一下相当通用的代码结构:
As the author of the R Inferno commented, there can be more subtle situations when dealing with NULL. Consider pretty general structure of code:
# x is some list(), now we want to process it.
> for (i in 1:n) x[[i]] <- some_function(...)
现在要知道,如果some_function()
返回NULL
,您可能将无法获得所需的内容:某些元素将消失.您应该使用lapply
函数.
看一下这个玩具示例:
Now be aware, that if some_function()
returns NULL
, you maybe will not get what you want: some elements will just disappear. you should rather use lapply
function.
Take a look at this toy example:
> initial <- list(1,2,3,4)
> processed_by_for <- list(0,0,0,0)
> processed_by_lapply <- list(0,0,0,0)
> toy_function <- function(x) {if (x%%2==0) return(x) else return(NULL)}
> for (i in 1:4) processed_by_for[[i]] <- toy_function(initial[[i]])
> processed_by_lapply <- lapply(initial, toy_function)
> processed_by_for
[[1]]
[1] 0
[[2]]
[1] 2
[[3]]
NULL
[[4]]
[1] 4
> processed_by_lapply
[[1]]
NULL
[[2]]
[1] 2
[[3]]
NULL
[[4]]
[1] 4
这篇关于将NULL分配给R中的列表元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!