迭代列表以获取其名称的值 [英] Iterate over list to get value by its name

查看:137
本文介绍了迭代列表以获取其名称的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很有效。但是有更有效/更简单的方法来获得输出

This works. But are there more efficient/simpler ways to get output?

test_list <- list(list("name"="A","property"=1),
              list("name"="B","property"=2),
              list("name"="C","property"=3))

myFunction <- function(arg1=NULL, arg2=NULL){
  arg1[[arg2]]
}

# works
output <- sapply(test_list, myFunction, "property")

# returns NULL 
# output <- sapply(test_list, `$`, "property")


推荐答案

我们可以指定匿名函数调用来进行提取

We can specify the anonymous function call to do the extraction

sapply(test_list, function(x) x$property)
#[1] 1 2 3

这篇关于迭代列表以获取其名称的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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