What is the Python equivalent (i.e. same output) for the R function density()?

Viewed 396

In R, there is a function called density(). The syntax for the function is -

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, …)

Of the different parameters, the ones I normally use are x (a numeric vector from which the estimate is computed) & adjust. I leave the other parameters to its default value (bw = "nrd0", n = 512 & kernel = "gaussian")

Is there a function in Python which takes the same (or equivalent) input AND returns the same output. The main output I am looking for are the 512 (since n = 512) x & y values.

1 Answers

Based on Oliver's suggestion, I used rpy2 to call R's density function from Python.

Code in 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

Code in 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])
Related