Reputation: 39
Teach me how to create a simple loop to calculate the following equation:
v0 = v * exp(k*d)
where v is a dataframe containing 17631 rows x 15 variables. For every v(row) it is multiplied with exp(k*d).
where k is a column vector containing 15 rate constant, one for each variable. where d is a row vector containing 17631 rows.
From my heart thanks!
Upvotes: 1
Views: 50
Reputation: 101129
If you want for loops, you can do it like below
# for loop by row
for (i in seq(nrow(v))) {
v0 <- rbind(v0,v[i,]*exp(d*k[i]))
}
# for loop by column
for (j in seq(ncol(v))) {
v0 <- cbind(v0,v[,j]*exp(d*k))
}
However, the most efficient way is using matrix to manipulate the data. Instead of using for loop, maybe you can try the code below
# matrix approach
v0 <- as.matrix(v)*exp(outer(d,k,"*"))
Upvotes: 1