I have two list m.list and the other r.list. The m.list has NA
values. For those that have NA
values, I would like to replace it with elements from r.list. The problem is when I use replace
function in R it is taking the index of the r.list and returns a incorrect value. Below is reproducible examples. IS there a way to replace value of one list based on the element name from another list?
m.list <- list(a= 1,b=NA,c=3,d=NA)
r.list <- list(a= 4,d=8,c=9)
mr.list <- replace(m.list, which(is.na(m.list)), r.list[which(is.na(m.list))])
Here is the output that I get b should be NA and d should be 8:
> mr.list
$a
[1] 1
$b
[1] 8
$c
[1] 3
$d
NULL
here is the desired output:
$a
[1] 1
$b
[1] NA
$c
[1] 3
$d
[1] 8
The easiest way to replace an item in a list is to use the Python indexing syntax. Indexing allows you to choose an element or range of elements in a list. With the assignment operator, you can change a value at a given position in a list.
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
Replace Multiple Values in a Python List. There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.
Here is an option with modifyList
modifyList(m.list, r.list[intersect(names(r.list), names(which(is.na(m.list))))])
#$a
#[1] 1
#$b
#[1] NA
#$c
#[1] 3
#$d
#[1] 8
If we split the code, the idea is to find the names
in 'm.list' where the value is missing and that is also found in 'r.list' (intersect
), then with modifyList
replace the values in 'm.list' with the subset of 'r.list'
nm1 <- intersect(names(r.list), names(which(is.na(m.list))))
modifyList(m.list, r.list[nm1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With