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

har*_*hal 48 null r list

我发现这种行为很奇怪,希望更有经验的用户分享他们的想法和解决方法.在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"
Run Code Online (Sandbox Code Playgroud)

列表元素向上移动.也许这是预期的,但我正在尝试实现一个函数,我合并列表中的两个元素并删除一个.我基本上想要丢失该列表索引或将其作为NULL.

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

谢谢你的建议.

Max*_*Max 60

好问题.

查看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
Run Code Online (Sandbox Code Playgroud)

更新:

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

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

现在要知道,如果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
Run Code Online (Sandbox Code Playgroud)

  • 这是'The R Inferno'的圈子8.1.55 http://www.burns-stat.com/pages/Tutor/R_inferno.pdf圈子8.1.56是一个更微妙的版本. (15认同)

Tyl*_*ker 8

你的问题对我来说有点混乱.

将null分配给现有对象实际上会删除该对象(例如,如果您有数据框并希望删除特定列,这可能非常方便).这就是你所做的.我无法确定你想要的是什么.你可以试试

sampleList[[2]] <- NA
Run Code Online (Sandbox Code Playgroud)

而不是NULL,但如果"我想失去"你的意思是删除它,那么你已经成功了.这就是为什么,"列表元素向上移动."


Nic*_*ton 6

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