You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历列表按名称取值:获取output是否有更高效简洁的方法?

Efficient & Concise Ways to Extract List Elements in R

Great question! The issue with using sapply(test_list, $, "property") is that the $ operator relies on non-standard evaluation—it looks for a literal name in the local environment instead of evaluating the second argument you pass. That’s why it returns NULL instead of the values you want.

Here are several cleaner, more efficient alternatives to get your desired output:

1. Use [[ with sapply (Simple Base R)

Unlike $, the [[ function properly evaluates its second argument, so this works perfectly and eliminates the need for a custom helper function:

output <- sapply(test_list, `[[`, "property")

This will return the exact same numeric vector c(1,2,3) as your original code, but in one concise line.

2. Use vapply for Type Safety (Efficient Base R)

If you know the type of output you expect (e.g., numeric values here), vapply is more efficient than sapply because it pre-defines the output type, skipping unnecessary internal checks:

output <- vapply(test_list, `[[`, numeric(1), "property")

This guarantees you get a numeric vector, making it safer for large datasets where type consistency matters.

3. Use purrr Functions (Tidyverse Style, Readable)

If you’re working with the tidyverse, purrr::map_dbl (or map_chr/map_int depending on your data type) offers intuitive, readable syntax:

library(purrr)
# Explicit syntax
output <- map_dbl(test_list, ~ .x[["property"]])
# Even shorter shorthand
output <- map_dbl(test_list, "property")

The map_* family makes it clear what output type you’re expecting, and it’s consistent with other tidyverse workflows.

4. Combine lapply and do.call (Base R, Fast for Large Lists)

For very large lists, this method can be faster than sapply by reducing overhead:

output <- do.call(c, lapply(test_list, `[[`, "property"))

It first extracts elements into a list with lapply, then collapses the list into a vector using do.call(c, ...).

All these methods avoid the need for a custom helper function while being more efficient or readable than your original approach. Which one you choose depends on whether you prefer base R or tidyverse syntax, and whether type safety or raw performance is your top priority.

内容的提问来源于stack exchange,提问作者nilsole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:06:30