简体   繁体   中英

writing a loop in R with a function

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!

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,"*"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM