如何比较唯一值的计数

时间:2017-06-01 11:43:37

标签: r compare

我需要检查A中变量PPT中每个唯一值的元素个数是否等于B中PPT中每个唯一值的元素个数,以及是否有任何唯一值仅对A或唯一值到B.

例如:

PPTa <- c("ppt0100109","ppt0301104","ppt0100109","ppt0100109","ppt0300249","ppt0100109","ppt0300249","ppt0100109","ppt0504409","ppt2303401","ppt0704210","ppt0704210","ppt0100109")
CNa <- c(110,54,110,110,49,10,49,110,409,40,10,10,110)
LLa <- c(150,55,150,150,45,15,45,115,405,45,5,15,50)
A <-data.frame(PPTa,CNa,LLa)

PPTb <- c("ppt0100200","ppt0300249","ppt0100109","ppt0300249","ppt0100109","ppt0764091","ppt2303401","ppt0704210","ppt0704210","ppt0100109")
CNb <- c(110,54,110,110,49,10,49,110,409,40)
LLb <- c(150,55,150,150,45,15,45,115,405,45)
B <-data.frame(PPTb,CNb,LLb)

在这种情况下,我们有这些独特的值会出现一定次数:

A$PPTa       TIMES
"ppt0100109" 6
"ppt0301104" 1
"ppt0300249" 2
"ppt0504409" 1
"ppt2303401" 1
"ppt0704210" 2

B$PPTb       TIMES
"ppt0100200" 1
"ppt0300249" 2
"ppt0100109" 3
"ppt0764091" 1
"ppt2303401" 1
"ppt0704210" 2

如果A和B中的唯一值都存在且元素数相同,我想创建一个值为0的新矩阵(或任何你建议的东西),如果两个数据帧中都存在,则值为1 A和B但元素数量不同,如果值仅存在于两个数据帧之一中,则值为2。 类似的东西:

A$PPTa       TIMES  OUTPUT
"ppt0100109" 6      1
"ppt0301104" 1      2
"ppt0300249" 2      0
"ppt0504409" 1      2
"ppt2303401" 1      0
"ppt0704210" 2      0

B$PPTb       TIMES  OUTPUT
"ppt0100200" 1      2
"ppt0300249" 2      0
"ppt0100109" 3      1
"ppt0764091" 1      2
"ppt2303401" 1      0
"ppt0704210" 2      0

1 个答案:

答案 0 :(得分:2)

您可以使用嵌套的ifelse语句

ifelse(do.call(paste0, A) %in% do.call(paste0, B), 0, ifelse(A$PPTa %in% B$PPTb, 1, 2))
#[1] 1 0 2 2 0 0
 ifelse(do.call(paste0, B) %in% do.call(paste0, A), 0, ifelse(B$PPTb %in% A$PPTa, 1, 2))
#[1] 1 2 0 0 2 0