0

I am trying to reproduce density.() function from R.

I have studied the topic post on stackoverflow before What is the Python equivalent (i.e. same output) for the R function density()?

And I have succefully built my code, however I got different result in R and Python.

Below is my R code

set.seed(1234)
x <- rnorm(10)
dx <- density(x, adjust=1)

my x and dx$x(which I expected to see same as output on python)

And here is my python code, I copy the same x and use the following code

from rpy2 import robjects
from rpy2.robjects.packages import importr
from rpy2.robjects import vectors
import numpy as np
X = [-1.2070657, 0.2774292, 1.0844412, -2.3456977, 0.4291247, 0.5060559, -0.5747400, -0.5466319, -0.5644520, -0.8900378]
print(" my X: ", X)
print("\n")

stats = importr("stats")

column = vectors.IntVector(X)

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

x = np.array(output[0])
y = np.array(output[1])
print("dx$x from R : ", x[:10] )
print("\n")
print("dx$y from R : ", y[:10])

enter image description here Also I am just trying to reproduce density.() function from R using Python,

I understand there might not be equivalent function, however R documenation says that this function is just kernel density estimates, but I still can't reproduce same result using sklearn.neighbors import KernelDensity with same parameters

Paga
  • 103
  • 1
  • 2
  • 9
  • I am trying to reproduce the result in Python using r2py. But also I am looking for the equivalent function density.() in Python – Paga Mar 14 '23 at 15:01
  • Likey the difference are due to the seed. In Python, you have not set the same seed as in R, so there are minor differences – mfg3z0 Mar 14 '23 at 15:02
  • The seed only generate the X, I am using the exact same X(vector) so it sould be the same result, This is my thought, if I got anything wrong, please tell me – Paga Mar 14 '23 at 15:04

1 Answers1

1

A kindly person just remind me of my vectors.IntVector(x) is the reason why the bug happened, just replace with vectors.FloatVector(x) can reproduce the result.

Paga
  • 103
  • 1
  • 2
  • 9