为R中的列表元素分配NULL?

我发现这种行为很奇怪,希望更有经验的用户分享他们的想法和解决方法。 在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]]) print(sampleList[[2]]) print(sampleList[[3]]) print(length(sampleList)) sampleList[[2]] <- NULL print(length(sampleList)) print(sampleList[[2]]) print(sampleList[[3]]) 

列表元素被上移。 也许这是预期的,但我想实现一个function,我合并列表中的两个元素,并删除一个。 我基本上想要失去那个列表索引或者将它作为NULL。

有什么办法,我可以分配NULL,并没有看到上述行为?

谢谢你的build议。

好问题。

查看R-FAQ :

在R中,如果x是一个列表,那么x [i] < – NULL和x [[i]] < – NULL从x中移除指定的元素。 其中第一个与S不兼容,在那里没有任何操作。 (请注意,您可以使用x [i] < – list(NULL)将元素设置为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 

更新:

正如R Inferno的作者所评论的那样,在处理NULL时可能会有更微妙的情况。 考虑相当一般的代码结构:

 # x is some list(), now we want to process it. > for (i in 1:n) x[[i]] <- some_function(...) 

现在请注意,如果some_function()返回NULL ,你可能不会得到你想要的:一些元素将会消失 。 你应该使用lapply函数。 看看这个玩具的例子:

 > 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赋值给一个已存在的对象会本质上删除该对象(例如,如果您有一个数据框并希望删除特定的列,这可能非常方便)。 这就是你所做的。 我无法确定你想要什么。 你可以试试

 sampleList[[2]] <- NA 

而不是NULL,但如果通过“我想输”你的意思是删除它,那么你已经成功了。 这就是为什么“列表元素上移了”。

 obj = list(x = "Some Value") obj = c(obj,list(y=NULL)) #ADDING NEW VALUE obj['x'] = list(NULL) #SETTING EXISTING VALUE obj