Multiplying All Elements of a Vector in R

multiplying all elements of a vector in R

You want prod:

R> prod(1:3)
[1] 6

Multiplying all elements of a vector by each element in a for loop in R

An option with outer where the default FUN is *. According to ?outer, usage is

outer(X, Y, FUN = "*", ...)

outer(x, scalar)

Multiply certain elements of a vector in R

A simple way to do this would be to turn your vector into a 30-row matrix and get the product of each column.

In the absence of a reproducible example, let's make one with a vector of 360 numbers drawn from a normal distribution:

set.seed(69)
vec <- rnorm(360)

We can turn vec into a 30 * 12 matrix by just doing matrix(vec, nrow = 30), which will fill the matrix by column. We then get the product of each column by using apply to apply the function prob to each column.

apply(matrix(vec, nrow = 30), 2, prod)
#> [1] -6.253460e-09 -4.413086e-09 -1.332389e-10 1.041448e-08 -1.779489e-08 1.255979e-10
#> [7] 3.463687e-13 -6.265196e-12 8.300651e-04 -1.041469e-10 4.256378e-09 1.439522e-09

multiply each element in a vector by the next element[r]

We can use cumprod if we need to return a vector of the same length with each value multiplied by the previous multiplied values.

cumprod(vector-1)

If we need to return a single product, then use prod

prod(vector-1)

Or with Reduce and *

Reduce(`*`, vector-1)

multiplying each value in one vector to all values in a second vector and creating a results matrix

What you are looking for is outer.

outer(x, y, FUN = "*")

If you want to use plus instead of multiplication you can change * to ·+·

outer(x, y, FUN = "+")

How to multiply elements of a list of vectors by elements of arrays one by one (matches element)

We can do an assignment based on the non-zero values. As the vector 'x' is having the same length as the number of non-zero values in each slice of 2D array, we can make use of the recycling of 'x'

a[a!=0] <- a[a!=0]*x 
dim(a)
#[1] 5 5 10

The values before the assignment

a[2,1,1]*x[1]
#[1] 1.462893
a[2,1,2]*x[1]
#[1] -0.2332104

after the assignment

a[2, 1, 1]
#[1] 1.462893
a[2, 1, 2]
#[1] -0.2332104

If we need to multiply by a list ('x'), then unlist it and create a matrix byrow=TRUE to get the elements multiplied correctly

a[a != 0] <- a[a != 0]*do.call(rbind, x)

The values before the assignment

a[2,1,1]*x[[1]][1]
#[1] 0.2297043

a[3,1,1]*x[[2]][1]
#[1] 0.1796345

Values after the assignment

a[2, 1, 1]
#[1] 0.2297043
a[3, 1, 1]
#[1] 0.1796345

data

set.seed(24)
a <- array(rnorm(5 * 5 * 10), c(5, 5, 10))
for(k in seq(dim(a)[3])) a[,,k][upper.tri(a[,,k], diag = TRUE)] <- 0

How to multiply a vector by function output element by element in R

As I said in my comment, a few lines of code can help clarity rather than obscure one-liners.

For your problem though, you can take advantage of the fact that R makes vectorized computations, that is, element-wise for each element of your tables.

So I would first reshape the data. Your example data is something like this, correct me if I'm wrong:

  • an array of dimension (n, n, N), which you described as a "list" of N arrays with n×n values, where the upper triangle is zero: they contain p = n(n-1)/2 non-zero values;
  • a list of p vectors of length N

Input data:

N <- 10
n <- 3
p <- n*(n-1)/2 # = 3

veclist <- list(
c(2.174090, 1.666464, 1.915763, 2.282967, 2.407327, 1.386437, 2.854528, 1.896338, 2.010713, 1.013387),
c(2.3020147, 3.3311029, -0.3103701, 3.2445878, 5.6261224, 5.2914477, -1.0621042, 3.0790536, 3.6186598, 4.1846937),
c(0.42808525, 4.02348551, -2.31160703, 5.56077594, 2.83856320, -0.02850242, 1.57480238, -2.68603276, 2.34598854, 4.14115289)
)

arr <- myfun(n, N)$a

reshape:

mat <- matrix(unlist(veclist), nrow=length(veclist), byrow=T)
dim(mat) # 3 10

# reformat the lower triangle data of arrays
flatarr <- sapply(1:N, function(i) arr[,,i][lower.tri(arr[,,i])])
dim(flatarr) # 3 10

do the element-wise multiplication:

res <- mat * flatarr

So really it was just a matter of reshaping.

Explanation

the sapply line above applies the same function to each of the 10 arrays. This function is:

function(i) {
# take the array number `i`
ai <- arr[,,i]
# get the lower triangle values
ai[lower.tri(ai)]
}

The output of sapply is automatically simplified to a matrix of dimension (3, 10), that is 3 lines and 10 columns.

Caution while flattening the array:

R takes matrix elements by columns. If the order you want is by line, you must transpose the array and take the upper.tri, so the sapply function is the following:

function(i) t(arr[,,i])[upper.tri(t(arr[,,i]))]

One-liner

(Once you defined veclist and arr <- myfun(n,N)$a)

res <- matrix(unlist(veclist), nrow=length(veclist), byrow=T) * sapply(1:N, function(i) arr[,,i][lower.tri(arr[,,i])])

How to multiply and divide all values in a vector using a list in R and how to filter a list

To select all the rows from the max value in Mn column you can use filter as -

library(dplyr)

df %>% filter(row_number() >= which.max(Mn))

# Ba Sr Mn
#1 1 1 2
#2 2 2 1
#3 2 2 1

with slice -

df %>% slice(which.max(Mn):n())

and in base R -

df[which.max(Mn):nrow(df), ]

You can apply this to list of dataframes using lapply/map -

lapply(list_df, function(df) df %>% filter(row_number() >= which.max(Mn)))

How to multiply only a specific element in a vector in R

From what you describe, it's a simple case of multiplying the fourth element by two and then replacing it in the original vector:

x[4] <- x[4] * 2

This simply multiplies the fourth element by two and then places it back into the original vector at the fourth position, thus overwriting the original value:

x <- c(1, 3, 4, 6, 4, 7)

> x
[1] 1 3 4 6 4 7

x[4] <- x[4] * 2

> x
[1] 1 3 4 12 4 7


Related Topics



Leave a reply



Submit