data.frame 中所有变量对的元素乘积求和
Summed multiplication of elements for all pairs of variables in a data.frame
除了 crossprod
之外,他们的任何 BASE 函数是否可以简单地执行 (.1*.3)+(.2*.4)
并为下面的 data.frame 输出 .11
?
注意:这是一个玩具示例,data.frame 可以有任意数量的列。
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
c(do.call("%*%", x))
[1] 0.11
甚至
x$a%*%x$b
我们可以使用Reduce
c(Reduce(`%*%`, x))
如果 x
如您所示是 data.frame
,您也可以在 tidyverse
中进行计算
x %>% rowwise() %>%
mutate(c = prod(c_across(everything()))) %>%
ungroup() %>%
summarise(c = sum(c)) %>%
pull(c)
[1] 0.11
尝试
> sum(do.call("*", x))
[1] 0.11
除了 crossprod
之外,他们的任何 BASE 函数是否可以简单地执行 (.1*.3)+(.2*.4)
并为下面的 data.frame 输出 .11
?
注意:这是一个玩具示例,data.frame 可以有任意数量的列。
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
c(do.call("%*%", x))
[1] 0.11
甚至
x$a%*%x$b
我们可以使用Reduce
c(Reduce(`%*%`, x))
如果 x
如您所示是 data.frame
,您也可以在 tidyverse
x %>% rowwise() %>%
mutate(c = prod(c_across(everything()))) %>%
ungroup() %>%
summarise(c = sum(c)) %>%
pull(c)
[1] 0.11
尝试
> sum(do.call("*", x))
[1] 0.11