The reason your code didn't work is that data$list[i]
should be replaced with data[[list[i]]]
. However, this whole code could be rewritten in two lines, which will make it both shorter and more efficient. I've changed your variable names so you're not overwriting the list
and data
functions:
dat <- data.frame(a=1:3, b=1:3, c=1:3, d=c(0.3,0.4,0.2))
lst <- c("a", "b", "c")
output.id <- lst
output.metric <- sapply(lst, function(x) sum(dat[,x]*dat$d)/sum(dat[,x]))
output.metric
# a b c
# 0.2833333 0.2833333 0.2833333
Another approach would be:
colSums(dat[,lst]*dat$d) / colSums(dat[,lst])
# a b c
# 0.2833333 0.2833333 0.2833333