Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中处理交叉积(与Python相比)_Python_R_Area - Fatal编程技术网

在R中处理交叉积(与Python相比)

在R中处理交叉积(与Python相比),python,r,area,Python,R,Area,在尝试将鞋带公式应用于该区域时,我在R和Python中遇到了一个有趣的区别。在Python中,可以直接使用nympy功能: import numpy as np import pandas as pd d = {"A": [2, 3, 1, 2], "B": [4, -8, 2, 4]} df = pd.DataFrame(data=d) area = 0.5 * np.abs(np.dot(df[df.columns[0]], np.roll(df[df.columns[1]], 1)) -

在尝试将鞋带公式应用于该区域时,我在
R
Python
中遇到了一个有趣的区别。在
Python
中,可以直接使用
nympy
功能:

import numpy as np
import pandas as pd
d = {"A": [2, 3, 1, 2], "B": [4, -8, 2, 4]}
df = pd.DataFrame(data=d)
area = 0.5 * np.abs(np.dot(df[df.columns[0]], np.roll(df[df.columns[1]], 1)) -
    np.dot(df[df.columns[1]], np.roll(df[df.columns[0]], 1)))
area
7.0

但是,我在使用
crossprod
%*%
)函数的
R
中也没有做到这一点,但仅在如下非常基本的迭代中:

get_area <- function(x, y) {
    add.val <- sub.val <- NA
    for(i in 1:(length(x) - 1)) {
        add.val[i] <- 0.5 * x[i] * (y[i + 1])
        sub.val[i] <- 0.5 * y[i] * (x[i + 1])
    }
    return(abs(sum(add.val) - sum(sub.val)))
}

get_area如果我们只定义一些helper函数,那么在R中就可以很快地实现。比如说

shift_left <- function(x)c(x[-1],x[1])
shift_right <- function(x)c(x[length(x)],x[-length(x)])

a <- c(2, 3, 1, 2)
b <- c(4, -8, 2, 4)
1/2 * abs(sum(a * (shift_left(b) - shift_right(b))))
# [1] 7

shift_left如果我们只定义一些helper函数,那么在R中就可以非常快地向前移动。比如说

shift_left <- function(x)c(x[-1],x[1])
shift_right <- function(x)c(x[length(x)],x[-length(x)])

a <- c(2, 3, 1, 2)
b <- c(4, -8, 2, 4)
1/2 * abs(sum(a * (shift_left(b) - shift_right(b))))
# [1] 7
左移