3

If I say l = list() and then I do l[[27]] = 100, it will create 26 other entries with the value NULL in them. Is there a way to avoid this?

For example if I run: l <- list(); for (i in c(4,7,1)) { l[[i]] <- i^1 }

It will creat a list with entries ranging from 1 to 7, and NULL values for all the ones I did not assign. How can I avoid these spurious entries?

4

3 回答 3

8

Use character values for the indices:

l <- list(); for (i in c(4,7,1)) { l[[as.character(i)]] <- i^1 }

> l
$`4`
[1] 4

$`7`
[1] 7

$`1`
[1] 1
于 2013-02-10T19:47:34.897 回答
4

我会避免for循环并使用lapply

> x <- c(4, 7, 1)
> setNames(lapply(x, `^`, 1), x)
$`4`
[1] 4

$`7`
[1] 7

$`1`
[1] 1
于 2013-02-10T20:06:30.250 回答
0

You could append to the list:

l <- list(); for (i in c(4,7,1)) { l <- append(l, i^1) }
于 2013-02-10T19:48:55.750 回答