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

Viewed 29

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
4 Answers
c(do.call("%*%", x))

[1] 0.11

or even

x$a%*%x$b

We can use Reduce

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

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

Try

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