如何在R中无需循环,利用列表元素作为向量索引计算均值?
Absolutely! lapply() is an ideal replacement for your loop here—it’s built to apply a function to every element of a list, which aligns perfectly with what you’re trying to do: calculate the mean of subsets of a defined by each vector in W.
First, let’s recap your original data setup for clarity:
p1 <- c(1,2,4) p2 <- c(4,6,5) p3 <- c(9,2,1) W <- list(p1,p2,p3) a <- c(0.2,0.1,0.7,0.8,0.8,0.8,0.4,0.5,0.9)
Using lapply() directly
You can pass W to lapply() along with an anonymous function that takes each index vector from W, subsets a, and computes the mean. By default, lapply() returns a list, so we’ll convert it to a vector (matching your original v output) using unlist() or simplify2array():
# Compute means with lapply, then convert to a vector v <- unlist(lapply(W, function(idx) mean(a[idx]))) # Or use simplify2array for the same result v <- simplify2array(lapply(W, function(idx) mean(a[idx])))
Verify consistency with your original loop
Let’s check that this gives the exact same result as your loop:
# Original loop implementation v_loop <- c(0,0,0) for(i in 1:3) { v_loop[i] <- mean(a[W[[i]]]) } # Compare results all.equal(v, v_loop) # Output: TRUE
Bonus: Even cleaner with purrr::map_dbl()
If you’re using the tidyverse, the purrr package’s map_dbl() function simplifies this further by directly returning a numeric vector (no need for unlist()):
library(purrr) v <- map_dbl(W, ~mean(a[.x]))
All of these approaches eliminate the explicit loop while keeping your code concise and idiomatic R.
内容的提问来源于stack exchange,提问作者Nyiannos

