How can I assign a list in R without creating a lot of new elements?
If I say l = list()
and then I do l[[27]] = 100
, it will create 26 other records with 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 }
A list will be generated with entries 1 through 7 and NULL values ββfor all those that I have not assigned. How can I avoid these false entries?
+3
Palace chan
source
to share
3 answers
Use signed values ββfor 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
+8
Matthew lundberg
source
to share
I would avoid the loop for
and use lapply
:
> x <- c(4, 7, 1)
> setNames(lapply(x, `^`, 1), x)
$`4`
[1] 4
$`7`
[1] 7
$`1`
[1] 1
+4
flodel
source
to share
You can add to the list:
l <- list(); for (i in c(4,7,1)) { l <- append(l, i^1) }
0
johannes
source
to share