rnorouzian
rnorouzian

Reputation: 7517

Summed multiplication of elements for all pairs of variables in a data.frame

Is their any BASE function other than crossprod to simply do (.1*.3)+(.2*.4) and output .11 for my data.frame below?

NOTE: This is a toy example, the data.frame can have any number of columns.

x = data.frame(a = c(.1, .2), b = c(.3, .4))

# Desired Output
(.1*.3)+(.2*.4) #= .11

crossprod(as.matrix(x))

# Current output
     a    b
a 0.05 0.11
b 0.11 0.25

Upvotes: 2

Views: 31

Answers (4)

ThomasIsCoding
ThomasIsCoding

Reputation: 102399

Try

> sum(do.call("*", x))
[1] 0.11

Upvotes: 0

AnilGoyal
AnilGoyal

Reputation: 26238

if x is a data.frame as you have shown, you may also do this math in tidyverse

x %>% rowwise() %>%
  mutate(c = prod(c_across(everything()))) %>%
  ungroup() %>%
  summarise(c = sum(c)) %>% 
  pull(c)

[1] 0.11

Upvotes: 1

akrun
akrun

Reputation: 887681

We can use Reduce

c(Reduce(`%*%`, x))

Upvotes: 2

Onyambu
Onyambu

Reputation: 79318

c(do.call("%*%", x))

[1] 0.11

or even

x$a%*%x$b

Upvotes: 4

Related Questions