如何将函数应用于数据框中的所有行组合?

Ale*_*lex 3 combinations r rows dataframe

我无法解决以下有关(通过限制列数简化)数据框“注释”的问题。

require(irr)
# data
annotations <- read.table(text = "Obj1    Obj2    Obj3
Rater1     a       b       c
Rater2     a       b       b
Rater3     a       b       c", header = TRUE, stringsAsFactors = FALSE)
Run Code Online (Sandbox Code Playgroud)

我想将 irr 包中的一致函数应用到行的所有组合(而不是排列),从而产生以下结果。

Agreement rater 1-2: 67%
Agreement rater 1-3: 100%
Agreement rater 2-3: 67%
Run Code Online (Sandbox Code Playgroud)

我需要对所有行组合运行一个函数,并且该函数需要访问多个/所有列。

我已经找出了问题的部分答案;我已经生成了一个正在运行的组合列表combn(rownames(annotations), 2),但我不知道如何在不编写低效的 for 循环的情况下使用该列表。

我尝试过应用,如 中所示apply(annotations, 1, agree),但我只能让它在一行上工作,而不是前面提到的组合。

有人知道如何继续吗?

更新:根据您的建议,以下解决方案有效。(我使用了kappa2irr 包而不是agree,但主要问题的解决方案保持不变。)

require(irr) #require the irr library for agreement calculations
annotations <- read.table(text = "Obj1    Obj2    Obj3
Rater1     a       b       c
Rater2     a       b       b
Rater3     a       b       c
Rater4     c       a       a", header = TRUE, stringsAsFactors = FALSE)

annotations <- t(annotations) #transpose annotations (rows become columns and vice versa)
kappa_list <- combn(colnames(annotations), 2, FUN=function(x) kappa_list[[length(kappa_list)+1]] = kappa2(matrix(c(annotations[,x[1]], annotations[,x[2]]), ncol=2))$value) #fill kappa_list with all pairs of columns (combinations of 2 raters) in annotations and, per combination, add a value to kappa_list that consists of the value of kappa2 applied to the current combination of raters
kappa_list # display the list of values
Run Code Online (Sandbox Code Playgroud)

Mar*_*son 6

你已经很接近了,你只需要apply关注结果combn即可。我不知道你指的是什么函数,但如果你插入你的函数,这应该是一样的。

首先,将结果另存为列表,因为添加名称更容易(我将两个条目组合在一起添加):

toCheck <- combn(rownames(annotations), 2, simplify = FALSE)

names(toCheck) <-
  sapply(toCheck, paste, collapse = " - ")
Run Code Online (Sandbox Code Playgroud)

然后,用它sapply来完成你的组合。在这里,我用来mean做比较,但在这里使用你需要的。如果您返回多个值,请使用lapplythen 处理结果以根据需要进行打印

sapply(toCheck, function(x){
  mean(annotations[x[1], ] == annotations[x[2], ])
})
Run Code Online (Sandbox Code Playgroud)

返回:

Rater 1 - Rater 2 Rater 1 - Rater 3 Rater 2 - Rater 3 
        0.6666667         1.0000000         0.6666667 
Run Code Online (Sandbox Code Playgroud)

  • 您可以在combn `combn(rownames(annotations), 2, FUN=function(x) Mean(annotations[x[1], ] == comments[x[2], ]))`中执行此操作 (4认同)