Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple values in a list in R

Tags:

list

r

matrix

If I have:

mylist <- lapply(1:10, function(x) matrix(NA, nrow=2, ncol=2))

And I want to replace, for example, the first, second and fifth element in the list with a:

mymatrix=cbind(c(1,1),c(1,1))

What can I do? I tried with:

mylist[c(1,2,5)]=mymatrix

But I can't substitute the new matrix because it's another list and with the [[]] I can only access to one element.

I think I have to use the lapply function but I can't figure out in which way.

like image 445
lgndrzzz Avatar asked Feb 25 '18 10:02

lgndrzzz


People also ask

How do I replace an item in a list in R?

replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.

How do I replace multiple characters in a string in R?

Use str_replace_all() method of stringr package to replace multiple string values with another list of strings on a single column in R and update part of a string with another string.

How do I rename multiple values in R?

To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.


1 Answers

Would this work for you?

mylist[c(1, 2, 5)] <- lapply(mylist[c(1, 2, 5)], function(x) x <- mymatrix)
like image 64
jay.sf Avatar answered Sep 24 '22 23:09

jay.sf