Arne
Arne

Reputation: 357

Overwrite single corresponding elements between two lists

I have a rather small question:

Imagine two lists "default" and "example", each is composed of 5 elements with identical names ("p1","p2,"p3","p4,"p5).

In case "p-values" of example have a value assigned to it, this value will remain.

In case a "p-value" has no value assigned to it (NA), the corresponding "p-value" of default should used to replace the gap.

I know you could loop through each element with a for loop and construct an if-loop within the for-loop but is there maybe a more elegant solution?

Here is an example case:

example=list(p1=2,p2=3,p3=4,p4=NA,p5=NA)
default=list(p1=26,p2=34,p3=43,p4=11,p5=98)

Upvotes: 1

Views: 34

Answers (1)

zx8754
zx8754

Reputation: 56149

Try this:

# assign matching p-value from default
example[ is.na(example) ] <- default[ is.na(example) ]

# result
example

# $p1
# [1] 2
# 
# $p2
# [1] 3
# 
# $p3
# [1] 4
# 
# $p4
# [1] 11
# 
# $p5
# [1] 98

Upvotes: 2

Related Questions