我有以下功能:
estimate = function(df, y_true) {
R = nrow(df)
y_estimated = apply(df, 2, mean)
((sqrt( (y_estimated - y_true)^2 / R)) / y_true) * 100
}
df = iris[1:10,2:4]
y_true = c(3, 1, 0.4)
estimate(df = df, y_true = y_true)
user:bird 提供了這個并且效果很好,但是,我還需要按組找到方法。因此,如果我們將 df 更改為df= iris[,2:5],我該怎么做才能通過 Species 找到每列的均值以在函式中使用。我認為這樣的事情會起作用 - 但不是運氣:
estimate = function(df, y_true, group) {
R = nrow(df)
y_estimated = df %>% group_by(group) %>% apply(df, 2, mean)
((sqrt( (y_estimated - y_true)^2 / R)) / y_true) * 100
}
df = iris[2:5]
y_true = c(3, 1, 0.4)
group=df$Species
estimate(df = df, y_true = y_true, group=group)
使用colMeans也沒有用。
這是這篇文章的擴展,它解釋了每個變數的用途。
uj5u.com熱心網友回復:
您可以保持函式原樣并將其按組應用于您的資料,而不是修改您的函式。如果您使用group_byand then group_modify,您傳遞給的函式的輸入group_modify是資料框,是該特定組中行的子集。
estimate = function(df, y_true) {
R = nrow(df)
y_estimated = apply(df, 2, mean)
((sqrt( (y_estimated - y_true)^2 / R)) / y_true) * 100
}
df = iris[2:5]
y_true = c(3, 1, 0.4)
library(dplyr, warn.conflicts = FALSE)
df %>%
group_by(Species) %>%
group_modify(~ as.data.frame.list(estimate(., y_true)))
#> # A tibble: 3 × 4
#> # Groups: Species [3]
#> Species Sepal.Width Petal.Length Petal.Width
#> <fct> <dbl> <dbl> <dbl>
#> 1 setosa 2.02 6.53 5.44
#> 2 versicolor 1.08 46.1 32.7
#> 3 virginica 0.123 64.4 57.5
由reprex 包于 2022-02-24 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432888.html
