简体   繁体   中英

How to multiply odd rows of your own matrix to get a vector without using loops

I need to write a function that calculates two vectors according to a given matrix BBB1: A - equal to the element product of odd rows of the matrix BBB1 and B – equal to the product of even rows. At the same time, you need to do this without using loops. I understand how to pull out even/odd rows, but I don't understand how to multiply the nth number of rows without a loop.

func <- function(BBB1) {
  A <- 1 
  B <- 1
  for (i in (1:dim(BBB1)[1])) {
    if (i %% 2 == 0) B <- B*BBB1[i, ]
    else A <- A*BBB1[i, ]
  }
  m <- list(A, B)
  return(m)
}

So I wrote down the function, but only through a loop.

Example:

"V1" "V2" "V3" "V4" "V5"
"1" 1 5 9 13 17
"2" 2 6 10 14 18
"3" 3 7 11 15 19
"4" 4 8 12 16 20

Desired result:

Vector AA= 3 35 99 195 323 
Vector BB= 8 48 120 224 360

It may be easier to subset with logical index recycled and then use prod in base R

apply(BBB1[c(TRUE, FALSE),], 2, prod)
 V1  V2  V3  V4  V5 
  3  35  99 195 323 
apply(BBB1[c(FALSE, TRUE),], 2, prod)
 V1  V2  V3  V4  V5 
  8  48 120 224 360 

Or use colProds from matrixStats

library(matrixStats)
> colProds(as.matrix(BBB1[c(TRUE, FALSE),]))
[1]   3  35  99 195 323
> colProds(as.matrix(BBB1[c(FALSE, TRUE),]))
[1]   8  48 120 224 360

data

BBB1 <- structure(list(V1 = 1:4, V2 = 5:8, V3 = 9:12, V4 = 13:16,
 V5 = 17:20), class = "data.frame",
 row.names = c("1", 
"2", "3", "4"))

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