首页 > 解决方案 > R 函数密度()的 Python 等效项(即相同的输出)是什么?

问题描述

在 R 中,有一个函数叫做density(). 该函数的语法是 -

density(x, bw = "nrd0", adjust = 1, kernel = c("gaussian", "epanechnikov", 
        "rectangular", "triangular", "biweight","cosine", "optcosine"),
        weights = NULL, window = kernel, width, give.Rkern = FALSE, n = 512, 
        from, to, cut = 3, na.rm = FALSE, …)

在不同的参数中,我通常使用的是x(计算估计值的数字向量) & adjust。我将其他参数保留为其默认值 ( bw = "nrd0", n = 512& kernel = "gaussian")

Python中是否有一个函数接受相同(或等效)的输入并返回相同的输出。我正在寻找的主要输出是 512(因为 n = 512)x 和 y 值。

标签: pythonrscikit-learnkernel-density

解决方案


根据 Oliver 的建议,我使用 rpy2 从 Python 调用 R 的密度函数。

R中的代码

column <- c(63, 45, 47, 28, 59, 28, 59)

output <- density(column, adjust=1) #all other parameters set to default

x <- output$x
y <- output$y

Python中的代码

from rpy2 import robjects
from rpy2.robjects.packages import importr
from rpy2.robjects import vectors
import numpy as np

stats = importr("stats")

column = vectors.IntVector([63, 45, 47, 28, 59, 28, 59])

output = stats.density(column, adjust=1)

x = np.array(output[0])
y = np.array(output[1])

推荐阅读