[R] Effective code for 2 vector multiplication?
Dimitri Liakhovitski
ld7631 at gmail.com
Tue Nov 20 00:41:39 CET 2007
Hello!
I have a data frame POPULATION populated with numeric values such that
dim(POPULATION) are: 100,000 (rows) and 3 (columns).
Also, I have a vector beta.vector that has 3 elements (all numeric values).
I want to create a new variable Y (a new column) in POPULATION such
that for each row of POPULATION, the value of Y equals the product of
2 vectors: 3 values of the corresponding row of POPULATION times
beta.vector.
Here is the code I wrote:
POPULATION$Y<-sapply(as.list(1:nrow(POPULATION)), function(x) {
x2<-as.numeric(POPULATION[x,]) %*% as.numeric(beta.vector)
return(x2)
} )
It calculates what I need and creates POPULATION$Y BUT - it takes 50
seconds (!!!)
My question: is there a more effective (faster) way of doing what I am
trying to do?
Thanks a lot!
Dimitri
More information about the R-help
mailing list