比较多行并在R或Excel中创buildmatrix

我有一个文件包含,多行如下

在file1中:

a 8|2|3|4 4 b 2|3|5|6|7 5 c 8|5|6|7|9 5 

a到a有4个重叠,同样a到b有2个重叠,为了检查各个实体之间的重叠,我需要生成一个具有上述细节的matrix,输出应该是一个matrix

  abc a 4 2 1 b 2 5 3 c 1 3 5 

请给我一个build议,怎么做? 有无论如何这样做使用Excel或使用shell脚本或使用R? 我已经写了下面的代码,但由于我不是一个好的编码器,不能得到打印在正确的格式输出。

 setwd('C:\\Users\\Desktop\\') newmet1<-file("file.txt") newmet2<-strsplit(readLines(newmet1),"\t") Newmet<-sapply(newmet2, function(x) x[2:length(x)], simplify=F ) for (i in 1:length(Newmet)) { for (j in 1:length(Newmet) { c <- ((intersect(Newmet[[i]], Newmet[[j]])) print (length(c)) } } 

编辑:感谢所有的答案..我得到了马蒂克斯。 在以下答案的帮助下同时使用excel和R。

如果数字在Sheet1!A1中的单独单元格中,请尝试

 =SUM(--ISNUMBER(MATCH(Sheet1!$A1:$E1,INDEX(Sheet1!$A$1:$E$3,COLUMN(),0),0))) 

从Sheet2开始!A1。

必须使用Ctrl Shift Enter作为数组公式input

不必从Sheet2开始的替代公式!A1

 SUM(--ISNUMBER(MATCH(Sheet1!$A1:$E1,INDEX(Sheet1!$A$1:$E$3,COLUMNS($A:A),0),0))) 

在这里输入图像说明

R中的函数返回每一列匹配的计数作为一个新的matrix

首先我们把你的数据放到一个R data.frame对象中:

 A <- c(8,2,3,4,NA) B <- c(2,3,5,6,7) C <- c(8,5,6,7,9) dataset <- data.frame(A,B,C) 

然后我们创build一个函数:

 count_matches <- function (x) { if (is.data.frame(x)) { y <- NULL for (i in 1:dim(x)[2]) { for (j in 1:dim(x)[2]) { count <- sum(x[[i]][!is.na(x[i])] %in% x[[j]][!is.na(x[j])]) y <- c(y, count) } } y <- matrix(y, dim(x)[2], ) colnames(y) <- names(x) rownames(y) <- names(x) return(y) } else { print('Argument must be a data.frame') } } 

我们在我们的数据集上testing函数:

 count_matches(dat) 

其中返回一个matrix:

  ABC A 4 2 1 B 2 5 3 C 1 3 5 

使用R:

 # dummy data df1 <- read.table(text = "a 8|2|3|4 4 b 2|3|5|6|7 5 c 8|5|6|7|9 5", as.is = TRUE) df1 # V1 V2 V3 # 1 a 8|2|3|4 4 # 2 b 2|3|5|6|7 5 # 3 c 8|5|6|7|9 5 # convert 2nd column to a splitted list myList <- unlist(lapply(df1$V2, strsplit, split = "|", fixed = TRUE), recursive = FALSE) names(myList) <- df1$V1 myList # $a # [1] "8" "2" "3" "4" # $b # [1] "2" "3" "5" "6" "7" # $c # [1] "8" "5" "6" "7" "9" # get overlap counts crossprod(table(stack(myList))) # ind # ind abc # a 4 2 1 # b 2 5 3 # c 1 3 5 

如果我们删除数据处理位,这个答案已经提供了类似的post: 相交列表元素的所有可能的组合