计算多个列中重复值的出现次数

Count occurrences of value in multiple columns with duplicates

我的问题非常类似于:

但是,那里提出的解决方案对我不起作用,因为在同一行中,该值可能出现两次,但我只想计算它出现的行数。我已经想出了一个解决方案,但它似乎太长了:

> toy_data = data.table(from=c("A","A","A","C","E","E"), to=c("B","C","A","D","F","E"))
> toy_data
   from to
1:    A  B
2:    A  C
3:    A  A
4:    C  D
5:    E  F
6:    E  E
> #get a table with intra-link count
> A = data.table(table(unlist(toy_data[from==to,from ])))
> A
   V1 N
1:  A 1
2:  E 1
A #get a table with total count
> B = data.table(table(unlist(toy_data[,c(from,to)])))
> B
   V1 N
1:  A 4
2:  B 1
3:  C 2
4:  D 1
5:  E 3
6:  F 1
> 
> # concatenate changing sign
> table = rbind(B,A[,.(V1,-N)],use.names=FALSE)
> # groupby and subtract
> table[,sum(N),by=V1]
   V1 V1
1:  A  3
2:  B  1
3:  C  2
4:  D  1
5:  E  2
6:  F  1

是否有一些函数可以在更少的行中完成这项工作?我想在 python 中我会连接 match() 和 match(),但找不到正确的语法

编辑:我知道这行得通 A=length(toy_data[from=="A"|to=="A",from]) 但我想避免各种 "A","B"... 之间的循环(而且我不知道如何以这种方式格式化输出)

您可以试试下面的代码

> toy_data[, to := replace(to, from == to, NA)][, data.frame(table(unlist(.SD)))]
  Var1 Freq
1    A    3
2    B    1
3    C    2
4    D    1
5    E    2
6    F    1

toy_data %>%
    mutate(to = replace(to, from == to, NA)) %>%
    unlist() %>%
    table() %>%
    as.data.frame()

这给出了

  . Freq
1 A    3
2 B    1
3 C    2
4 D    1
5 E    2
6 F    1

使用data.table

library(data.table)
toy_data[from == to, to := NA][, .(to = na.omit(c(from, to)))][, .N, to]

按照 akrun 的建议使用 to:=NA,可以将结果包装在 table(unlist()) 中并转换为 data.table

data.table(table(unlist(toy_data[from==to, to:=NA, from])))

您可以只对 to 向量进行子集化:

data.table(table(unlist(toy_data[,c(from,to[to!=from])])))

   V1 N
1:  A 3
2:  B 1
3:  C 2
4:  D 1
5:  E 2
6:  F 1