Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace list element with another list element based on name

Tags:

replace

list

r

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
like image 243
forecaster Avatar asked Mar 11 '18 16:03

forecaster


People also ask

How do you replace an item in a list with an item from another list?

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.

How do you replace values in a list with values in another list Python?

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.

How do you replace multiple elements in a list in Python?

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.


1 Answers

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])
like image 62
akrun Avatar answered Nov 10 '22 11:11

akrun