Q:

How do I apply weights to particular columns in a dataframe to aggregate a new 'score' column?

By way of reproducible example, say you have the following R dataframe:
set.seed(100)
df <- data.frame(Name=letters[1:5], Apples=sample(1:10, 5), Oranges=sample(1:10, 5), Bananas=sample(1:10, 5), Dates=sample(1:10, 5))

And you want to apply the following weights to the dataframe:
Weights <- c(Apples = "3", Oranges = "2", Bananas = "1")

To produce a new aggregate score column. So for example the first row (row 'a') would have the following score:
(3*4 + 2*5 + 1*7) = 29

And row b:
(3*3 + 2*8 + 1*8) = 33

What code I write to do this automatically?
Note that the weights may not be in the same order as the columns in the dataframe, nor will there necessarily be a weight for every numeric column in the dataframe (hence why in this example there is no weight for 'dates').

A:

We can use rowSums after multiplying the subset of columns in 'df' by the corresponding elements in 'Weights' (by replicating the 'Weights')
rowSums(df[names(Weights)]*as.numeric(Weights)[col(df[names(Weights)])])
#[1] 29 33 24 20 36

