user2987808
user2987808

Reputation: 1437

reassign values in a list without looping

test <- list(a = list("first"= 1, "second" = 2), 
         b = list("first" = 3, "second" = 4))

In the list above, I would like to reassign the "first" elements to equal, let's say, five. This for loop works:

for(temp in c("a", "b")) {
  test[[temp]]$first <- 5
}

Is there a way to do the same using a vectorized operation (lapply, etc)? The following extracts the values, but I can't get them reassigned:

lapply(test, "[[", "first")

Upvotes: 1

Views: 101

Answers (2)

talat
talat

Reputation: 70336

You can do it like this:

test <- lapply(test, function(x) {x$first <- 5; x})

Upvotes: 3

James
James

Reputation: 66874

Here is a vectorised one-liner using unlist and relist:

relist((function(x) ifelse(grepl("first",names(x)),5,x))(unlist(test)),test)
$a
$a$first
[1] 5

$a$second
[1] 2


$b
$b$first
[1] 5

$b$second
[1] 4

Upvotes: 4

Related Questions