将公式转换为函数
Turning a formula to a function
我有以下相对估计误差的公式,我正试图将其转化为一个函数来衡量测量精度。
其中:
Y_estimated = 测试中的观测值 df
y_true = 我们试图估计的真实值(在代码中表示为 p_true)
R = 每次迭代的观察次数 (n=3)
我的数据格式如下:
# dataframe
test<- iris[1:3,1:4]
# make a vector that shows the true population value for each column in the dataframe
p_true<- c(5, 3, 1, 0.3)
# function
estimate = function(df, y_true) {
((sqrt(sum((df - y_true) ^ 2)) / 3) / y_true) * 100
}
y_true <- p_true
final2 <- test %>%
group_modify( ~ as.data.frame(estimate(., p_true)))
目标是输出 1 行 4 个精度估计值(每个变量一个)。除了将当前输出格式放入 1 列和 4 行而不是 4 列和 1 行之外,我不确定该函数是否设置正确,因为这些值比我期望的要极端得多。
如果有人能确认我的功能是否设置正确and/or如何使输出格式正确,我将不胜感激。
没有。它不做你认为它正在做的事情。查看test - y_true
的结果。这些值不是您所期望的,因为您是从矩阵 (test
) 中减去一个向量 (y_true
)。 R 跨行应用向量,因此 5.1 - 5 = 0.1, 4.9 - 3 = 1.9, 4.7 - 1 = 3.7:
test - y_true
# Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1 0.1 3.2 0.4 -2.8
# 2 1.9 -2.0 1.1 -0.8
# 3 3.7 0.2 -3.7 -0.1
有几种方法可以解决这个问题,这里有 3 种:
test - matrix(y_true, 3, 4, byrow=TRUE)
t(t(test) - y_true)
sweep(test, 2, y_true, "-")
# These will produce what you are expecting:
# Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1 0.1 0.5 0.4 -0.1
# 2 -0.1 0.0 0.4 -0.1
# 3 -0.3 0.2 0.3 -0.1
您还需要使用 colSums()
而不是 sum()
。那么您的其余代码应该可以工作:
sqrt(colSums((test - matrix(y_true, 3, 4, byrow=TRUE))^2) / 3) / y_true * 100
# Sepal.Length Sepal.Width Petal.Length Petal.Width
# 3.829708 10.363755 36.968455 33.333333
我有以下相对估计误差的公式,我正试图将其转化为一个函数来衡量测量精度。
其中:
Y_estimated = 测试中的观测值 df
y_true = 我们试图估计的真实值(在代码中表示为 p_true)
R = 每次迭代的观察次数 (n=3)
我的数据格式如下:
# dataframe
test<- iris[1:3,1:4]
# make a vector that shows the true population value for each column in the dataframe
p_true<- c(5, 3, 1, 0.3)
# function
estimate = function(df, y_true) {
((sqrt(sum((df - y_true) ^ 2)) / 3) / y_true) * 100
}
y_true <- p_true
final2 <- test %>%
group_modify( ~ as.data.frame(estimate(., p_true)))
目标是输出 1 行 4 个精度估计值(每个变量一个)。除了将当前输出格式放入 1 列和 4 行而不是 4 列和 1 行之外,我不确定该函数是否设置正确,因为这些值比我期望的要极端得多。
如果有人能确认我的功能是否设置正确and/or如何使输出格式正确,我将不胜感激。
没有。它不做你认为它正在做的事情。查看test - y_true
的结果。这些值不是您所期望的,因为您是从矩阵 (test
) 中减去一个向量 (y_true
)。 R 跨行应用向量,因此 5.1 - 5 = 0.1, 4.9 - 3 = 1.9, 4.7 - 1 = 3.7:
test - y_true
# Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1 0.1 3.2 0.4 -2.8
# 2 1.9 -2.0 1.1 -0.8
# 3 3.7 0.2 -3.7 -0.1
有几种方法可以解决这个问题,这里有 3 种:
test - matrix(y_true, 3, 4, byrow=TRUE)
t(t(test) - y_true)
sweep(test, 2, y_true, "-")
# These will produce what you are expecting:
# Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1 0.1 0.5 0.4 -0.1
# 2 -0.1 0.0 0.4 -0.1
# 3 -0.3 0.2 0.3 -0.1
您还需要使用 colSums()
而不是 sum()
。那么您的其余代码应该可以工作:
sqrt(colSums((test - matrix(y_true, 3, 4, byrow=TRUE))^2) / 3) / y_true * 100
# Sepal.Length Sepal.Width Petal.Length Petal.Width
# 3.829708 10.363755 36.968455 33.333333