3

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.

Ral'akkai
  • 53
  • 5
  • I can't seem to find an actual equivalent (yet), so all I can give is a hint for making a function. To get the specified bandwidth (`bw = "nrd0`), you can use certain algorithms from [here](https://stackoverflow.com/questions/38337804/is-there-a-scipy-numpy-alternative-to-rs-nrd0). –  Jan 17 '21 at 11:04
  • I don't think you should expect an equivalent function to necessarily exist. There are implementations in different languages. `scipy.stats` has various kde implementations, while `scikit-learn` has alternatives for visualization. they are not the same. But `R` and `Python` has excellent packages for bi-lingual programming. So if the output of `density` is what you want, install both on your machine and use [`rpy2`](https://rpy2.github.io/) to use the function from python. – Oliver Jan 17 '21 at 11:14
  • 1
    Thanks @Oliver. I used rpy2 and am able to use the Density function in the same manner as my R script. I will post my code as an answer. – Ral'akkai Jan 17 '21 at 12:47

1 Answers1

2

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])
Ral'akkai
  • 53
  • 5