gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:38:46 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com