﻿ 为R中的列表元素分配NULL？ - 代码日志

#### 为R中的列表元素分配NULL？

``````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]])
``````

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
``````

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

``````> 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
``````
http://stackoverflow.com/questions/7944809/assigning-null-to-a-list-element-in-r