Iterate over list to get value by its name

二次信任 提交于 2019-12-24 10:59:43

问题


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")

回答1:


We can specify the anonymous function call to do the extraction

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


来源:https://stackoverflow.com/questions/50510682/iterate-over-list-to-get-value-by-its-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!