Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a list of lists with lapply

Tags:

list

r

lapply

I have list of lists that are all the same structure and I want to alter one element of each of the lists in the second tier. In other words, I have a single list with objects x, y & z. This list is repeated multiple times in another list. I need to change x in each of these lists. What is the best way to do this?

My current approach is to create a small function that does the change I want and then re-create the list. But there is something that makes me think that there is simpler way to do this?

The code below shows my approach, which is fine for my toy example - but the real context the object is more complicated, so I don't really want to have to recreate it multiple times considering I only change one value. I could do it this way, it just feels convoluted.

l = list(x = 1:3, y = "a", z = 9)
test = list(l, l, l)

standardize = function(obj){
  obj$x = obj$x / max(obj$x)
  list(obj$x, obj$y, obj$z)
}

lapply(test, function(e) standardize(e))
like image 373
SamPassmore Avatar asked Sep 02 '25 05:09

SamPassmore


1 Answers

Simply return the modified obj instead of re-creating a list.

standardize = function(obj){
  obj$x <- obj$x / max(obj$x)
  obj
}

Bonus: the names of obj's elements are now preserved.

like image 110
asachet Avatar answered Sep 05 '25 02:09

asachet