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

时间:2018-01-18 21:49:33

标签: 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的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或包中)?这对我来说是一个相对简单的问题,但是通过尝试解决它,我意识到这很奇怪,至少在我脑海里。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

以下是来自http://www.cookbook-r.com/Manipulating_data/Converting_between_data_frames_and_contingency_tables/的一些公共域代码,我过去常常这样做。


# Convert from data frame of counts to data frame of cases.
# `countcol` is the name of the column containing the counts
countsToCases <- function(x, countcol = "Freq") {
    # Get the row indices to pull from x
    idx <- rep.int(seq_len(nrow(x)), x[[countcol]])

    # Drop count column
    x[[countcol]] <- NULL

    # Get the rows from x
    x[idx, ]
}