SamPassmore SamPassmore -4 years ago 88
R Question

Changing a list of lists with 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))

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download