【发布时间】:2021-09-06 04:03:34
【问题描述】:
我读到可以将数据帧存储在带有嵌套的数据帧的列中: https://tidyr.tidyverse.org/reference/nest.html
是否也可以将表存储在数据框的列中?
原因是我想用 Caret 计算数据帧的每个子组的 Kappa。虽然 caret::confusionMatrix(t) 需要一个表格作为输入。
在下面的示例代码中,如果我一次计算完整数据帧的 Kappa,则可以正常工作:
library(tidyverse)
library(caret)
# generate some sample data:
n <- 100L
x1 <- rnorm(n, 1.0, 2.0)
x2 <- rnorm(n, -1.0, 0.5)
y <- rbinom(n, 1L, plogis(1 * x1 + 1 * x2))
my_factor <- rep( c('A','B','C','D'), 25 )
df <- cbind(x1, x2, y, my_factor)
# fit a model and make predictions:
mod <- glm(y ~ x1 + x2, "binomial")
probs <- predict(mod, type = "response")
# confusion matrix
probs_round <- round(probs)
t <- table(factor(probs_round, c(1,0)), factor(y, c(1,0)))
ccm <- caret::confusionMatrix(t)
# extract Kappa:
ccm$overall[2]
> Kappa
> 0.5232
尽管如果我尝试使用 group_by 为每个因子生成 Kappa 作为子组(请参见下面的代码),但它不会成功。我想我需要以某种方式将t 嵌套在df 中,尽管我不知道如何:
# extract Kappa for every subgroup with same factor (NOT WORKING CODE):
df <- cbind(df, probs_round)
df <- as.data.frame(df)
output <- df %>%
dplyr::group_by(my_factor) %>%
dplyr::mutate(t = table(factor(probs_round, c(1,0)), factor(y, c(1,0)))) %>%
summarise(caret::confusionMatrix(t))
Expected output:
>my_factor Kappa
>1 A 0.51
>2 B 0.52
>3 C 0.53
>4 D 0.54
这是正确的吗?这可能吗? (由于样本数据的随机性,Kappa 的确切值会有所不同)
非常感谢!
【问题讨论】:
-
不清楚你想要什么,你能分享你的预期输出吗?此外,您下次可能想尝试使用
reprex::reprex(),您的示例并非 100% 可重现。 -
@Dan Chaltiel 对不起,我已经修改了我上面的例子。
标签: r dplyr datatable nested r-caret