I have a csv with multiple columns, with names like XX_0, XXX_1,...XXX_20
I want to add a new column to each row of the csv that is weighted sum of these columns. E.g DataFrame$WeightedX = 1*DataFRame$X_0+2*DataFRame$X_1+....+21**DataFRame$X_21
Is there a way to do this programmatically?
The code under manual works. I want to do something along the lines of the programmatic attempt below
Manual version works
findWeightedSumManual <- function(x){
weights <- c(1,10,20)
return(weights[1]*x$X_0 + weights[2]*x$X_1 + weights[3]*x$X_2)
}
Data = data.table(1:3,2:4,5:7)
colnames(Data) <- c('X_0', 'X_1', 'X_2')
Data$WeightedSum1 <- findWeightedSumManual(Data)
But I want to make it programmatic along the lines of
findWeightedSum <- function(x){
weights <- c(1,10,20)
sum <- 0
for (i in 1:ncol(x)) {
colName <- paste("X_",i,sep="")
sum <- sum + weights[i]*x$colName
}
return(sum)
}
Data = data.table(1:3,2:4,5:7)
colnames(Data) <- c('X_0', 'X_1', 'X_2')
Data$WeightedSum2 <- findWeightedSum(Data)
Data