R:将列联表转换为长数据框

标签 r dataframe

考虑给您一个汇总的交叉表,如下所示:

kdat <- data.frame(positive = c(8, 4), negative = c(3, 6),
                   row.names = c("positive", "negative"))
kdat
#>          positive negative
#> positive        8        3
#> negative        4        6

现在您要计算 Cohen's Kappa,这是一个用于确定两个评估者之间一致性的统计量。给定这种格式的数据,您可以使用 psych::cohen.kappa :
psych::cohen.kappa(kdat)$kappa
#> Warning in any(abs(bounds)): coercing argument of type 'double' to logical
#> [1] 0.3287671

这让我很生气,因为我更喜欢我的数据又长又细,这让我可以使用 irr::kappa2 .出于任意原因,我更喜欢类似的功能。所以我组装了这个函数来重新格式化我的数据:
longify_xtab <- function(x) {
  nm <- names(x)
  # Convert to table
  x_tab <- as.table(as.matrix(x))
  # Just in case there are now rownames, required for conversion
  rownames(x_tab) <- nm
  # Use appropriate method to get a df
  x_df <- as.data.frame(x_tab)

  # Restructure df in a painful and unsightly way
  data.frame(lapply(x_df[seq_len(ncol(x_df) - 1)], function(col) {
    rep(col, x_df$Freq)
  }))
}

该函数返回以下格式:
longify_xtab(kdat)
#>        Var1     Var2
#> 1  positive positive
#> 2  positive positive
#> 3  positive positive
#> 4  positive positive
#> 5  positive positive
#> 6  positive positive
#> 7  positive positive
#> 8  positive positive
#> 9  negative positive
#> 10 negative positive
#> 11 negative positive
#> 12 negative positive
#> 13 positive negative
#> 14 positive negative
#> 15 positive negative
#> 16 negative negative
#> 17 negative negative
#> 18 negative negative
#> 19 negative negative
#> 20 negative negative
#> 21 negative negative

...让您通过 irr::kappa2 计算 Kappa :
irr::kappa2(longify_xtab(kdat))$value
#> [1] 0.3287671

我的问题是:
有没有更好的方法来做到这一点(在基础 R 中或使用包)?我觉得这是一个相对简单的问题,但通过尝试解决它,我意识到这非常棘手,至少在我的脑海中是如此。

最佳答案

kdat <- data.frame(positive = c(8, 4), 
                   negative = c(3, 6),
                   row.names = c("positive", "negative"))

library(tidyverse)

kdat %>%
  rownames_to_column() %>%            # set row names as a variable
  gather(rowname2,value,-rowname) %>% # reshape
  rowwise() %>%                       # for every row
  mutate(value = list(1:value)) %>%   # create a series of numbers based on the value
  unnest(value) %>%                   # unnest the counter
  select(-value)                      # remove the counts

# # A tibble: 21 x 2
#    rowname  rowname2
#      <chr>    <chr>   
# 1 positive positive
# 2 positive positive
# 3 positive positive
# 4 positive positive
# 5 positive positive
# 6 positive positive
# 7 positive positive
# 8 positive positive
# 9 negative positive
# 10 negative positive
# # ... with 11 more rows

关于R:将列联表转换为长数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48330888/

相关文章:

r - 使用 clusplot 绘制以 0 为中心坐标的聚类

r - 如何根据另一列的另一个值在一列中收集数据

python - Pandas - 将列子集行与主列中的匹配值对齐

r - 检查一个数据框列中的值是否存在于第二个数据框中

python - 按列位置掩码 2 df

r - 通过行名访问数据框给我的是 NA 而不是我期望的值

r - 在 RStudio 的 R 包中记录 R6 类和方法

r - 概率分类 - R

html - R Shiny 框内容背景色

python - 创建一个新列取决于两个不同数据帧中列中的匹配字符串