R:根据数据框的大小调整函数

R: Adapting a Function Based on the Size of a Data Frame

我正在使用 R 编程语言。

我编写了以下代码,从正态分布中生成 20 个随机点,然后绘制似然函数:

# generate random data
x1 = rnorm(1,5,5)
x2 = rnorm(1,5,5)
x3 = rnorm(1,5,5)
x4 = rnorm(1,5,5)
x5 = rnorm(1,5,5)
x6 = rnorm(1,5,5)
x7 = rnorm(1,5,5)
x8 = rnorm(1,5,5)
x9 = rnorm(1,5,5)
x10 = rnorm(1,5,5)
x11 = rnorm(1,5,5)
x12 = rnorm(1,5,5)
x13 = rnorm(1,5,5)
x14 = rnorm(1,5,5)
x15 = rnorm(1,5,5)
x16 = rnorm(1,5,5)
x17 = rnorm(1,5,5)
x18 = rnorm(1,5,5)
x19 = rnorm(1,5,5)
x20 = rnorm(1,5,5)

 
# Define Likelihood Function (from here: #https://www.statlect.com/fundamentals-of-statistics/normal-distribution-maximum-likelihood - I broke the Likelihood Function into 4 parts "a", "b", "c", "d" : then I added them together to make the full Likelihood Function "f") 

  my_function <- function(mu,sigma) {

 
n = 20

a = -n/2*log(2*pi)

b = -n/2*log(sigma^2)

c = -1/(2*sigma^2)

d = (x1-mu)^2 + (x2-mu)^2 + (x3-mu)^2 + (x4-mu)^2 + (x5-mu)^2 + (x6-mu)^2 + (x7-mu)^2 + (x8-mu)^2 + (x9-mu)^2 + (x10-mu)^2 + (x11-mu)^2 + (x12-mu)^2 + (x13-mu)^2 + (x14-mu)^2 + (x15-mu)^2 + (x16-mu)^2 + (x17-mu)^2 + (x18-mu)^2 + (x19-mu)^2 + (x20-mu)^2     


f = a + b + c + d

    }


# plot results

library(plotly)

input_1 <- seq(-20, 20,0.1)

input_2 <- seq(-20,20, 0.1)


z <- outer(input_1, input_2, my_function)


plot_ly(x = input_1, y = input_2, z = z) %>% add_surface()

我的问题:有人可以告诉我如何制作此代码的更“高效”版本吗?

要将数据存储到 data.frame 中,您只需执行以下操作:

my_data <- rnorm(20, 5, 5)
df <- data.frame(x = my_data, <other_columns>) 

请注意,其他列的长度必须相同。如果不是这种情况,最好将这些数字分开。

然后在 my_function 内,您可以拥有:

d = sum((df$my_data - mu)^2)

如果您不使用数据框,则改为:

d = sum((my_data - mu)^2)