遍历列表按名称取值:获取output是否有更高效简洁的方法?
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

