替换列表列表中的元素 [英] Replacing elements in a list of lists

查看:46
本文介绍了替换列表列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R 中的 apply 函数是一种简化 for 循环以获得输出的好方法.是否有等效的函数可以帮助人们在替换向量值时避免 for 循环?这可以通过示例更好地理解...

The apply functions in R are a nice way to simplify for loops to get to an output. Is there an equivalent function that helps one avoid for loops when replacing the values of a vector? This is better understood by example...

# Take this list for example
x = list( list(a=1,b=2), list(a=3,b=4), list(a=5,b=6) )

# To get all of the "a" elements from each list, I can do
vapply(x,"[[",1,"a")
[1] 1 3 5

# If I want to change all of the "a" elements, I cannot do
vapply(x,"[[",1,"a") = 10:12
Error in vapply(x, "[[", 1, "a") = 10:12 : 
  could not find function "vapply<-"
# (this error was expected)

# Instead I must do something like this...
new.a = 10:12
for(i in seq_along(x)) x[[i]]$a = new.a[i]

有没有比使用循环更简单或更快的替代方法?

Is there a simpler or faster alternative to using a loop?

推荐答案

一种选择是先unlist列表x,然后替换名为的值"a",然后根据x的列表结构relist新列表u.

One option would be to first unlist the list x, then replace the values named "a", and then relist the new list u based on the list structure of x.

u <- unlist(x)
u[names(u) == "a"] <- 10:12
relist(u, x)

这篇关于替换列表列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆