OctaveCello
OctaveCello

Reputation: 43

Replace item in list with list

Given a list Z <- list("a"=1, "b"=2, "d"=3), how do I replace, for example, items 1 and 3 with lists so that the final object is, for example:

> Z
$a
[[1]] 
[1] TRUE
[[2]] 
[1] "apple"

$b
[1] 2

$d
[[1]] 
[1] TRUE
[[2]] 
[1] "apple"

Using replace(Z, c(1,3), list(TRUE, "apple")) instead replaces item 1 with TRUE and item 3 with "apple", as does using the assign operator Z[c(1,3)] <- list(TRUE, "apple").

Any suggestions?

Upvotes: 1

Views: 602

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522396

Here is a solution using lapply. I spent about 10-15 minutes fumbling over the question, and the list replacements kept getting truncated at only the first element. The problem is that I was using ifelse to decide whether to return a list, or the original element. Switching to a formal if else statement fixed that problem.

Z <- list("a"=1, "b"=2, "d"=3)
lst <- list(TRUE, "apple")
indices <- c(1, 3)
output <- lapply(Z, function(x) {
    if (x %in% indices) { lst } else { x }
})

output

$a
$a[[1]]
[1] TRUE

$a[[2]]
[1] "apple"


$b
[1] 2

$d
$d[[1]]
[1] TRUE

$d[[2]]
[1] "apple"

Upvotes: 0

Andrew Gustar
Andrew Gustar

Reputation: 18425

This will do it...

Z <- list("a"=1, "b"=2, "d"=3)

Z[c(1,3)] <- list(list(TRUE,"apple"))

Z
$`a`
$`a`[[1]]
[1] TRUE

$`a`[[2]]
[1] "apple"


$b
[1] 2

$d
$d[[1]]
[1] TRUE

$d[[2]]
[1] "apple"

Or Z <- replace(Z,c(1,3),list(list(TRUE,"apple"))) will do the same thing.

Upvotes: 2

Related Questions