Pierre Lapointe
Pierre Lapointe

Reputation: 16277

Replace empty element in a list using sapply

I have two lists. The first one has an empty element. I'd like to replace that empty element with the first vector of the third list element of another list.

l1 <- list(a=1:3,b=4:9,c="")
l2 <- list(aa=11:13,bb=14:19,cc=data.frame(matrix(100:103,ncol=2)))

l1[sapply(l1, `[[`, 1)==""] <- l2[[3]][[1]]

Using sapply, I can identify which elements are empty. However, when I try to assign a vector to this empty element: I get this error message:

Warning message: In l1[sapply(l1, [[, 1) == ""] <- l2[[3]][[1]] :
number of items to replace is not a multiple of replacement length

This is only a warning, but the result I get is not the one I want. This is the l1 I get:

> l1
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100

This is what I need (two elements in $c):

> l1
$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100 101

Upvotes: 0

Views: 954

Answers (2)

Andrew Gustar
Andrew Gustar

Reputation: 18425

Just use l2[[3]][1] on the right hand side (single [ not [[)

Upvotes: 2

Rich Scriven
Rich Scriven

Reputation: 99361

The right-hand side should be a list, since you're replacing a list element. So you want that to be

... <- list(l2[[3]][[1]])

In addition, you might consider using !nzchar(l1) in place of sapply(...) == "". It might be more efficient. The final expression would be:

l1[!nzchar(l1)] <- list(l2[[3]][[1]])

giving the updated l1:

$a
[1] 1 2 3

$b
[1] 4 5 6 7 8 9

$c
[1] 100 101

Upvotes: 1

Related Questions