如何在数据框的列中嵌套表?

用户2165379

我读到可以将数据帧存储在带有嵌套的数据帧列中: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 的确切值会有所不同)

非常感谢!

克提乌

您可以跳过mutate()给您带来麻烦的中间环节:

library(dplyr)
library(caret)

df %>%
    group_by(my_factor) %>% 
    summarize(t = confusionMatrix(table(factor(probs_round, c(1,0)),
                                        factor(y, c(1,0))))$overall[2])

返回:

# A tibble: 4 x 2
  my_factor     t
  <chr>     <dbl>
1 A         0.270
2 B         0.513
3 C         0.839
4 D         0.555

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章