【问题标题】:Matching the combination but how the comma? I am confused但如何匹配逗号组合?我很困惑
【发布时间】:2016-03-23 18:58:57
【问题描述】:

我会问一个问题。如果您愿意尝试,这将非常有帮助。谢谢 我这里有一个向量....

[1] "I1,I2" "I1,I3" "I1,I4" "I1,I5" "I2,I3" "I2,I4"
[7] "I2,I5" "I3,I4" "I3,I5" "I4,I5"

那么,我想通过下面的向量来匹配这个...

[1] "I1,I2,I5"    "I2,I4"       "I2,I3"      
[4] "I1,I2,I4"    "I1,I3"       "I2,I3"      
[7] "I1,I3"       "I1,I2,I3,I5" "I1,I2,I3"  


hits <- sapply(1:length(a.new.list), function(j) pmatch(result,a.new.list[j]))
colnames(hits) <- a.new.list
rownames(hits) <- result

apply(hits,1, sum,na.rm=TRUE)

I1,I2 I1,I3 I1,I4 I1,I5 I2,I3 I2,I4 I2,I5 I3,I4 I3,I5 I4,I5 
4     2     0     0     2     1     0     0     0     0

但我所期望的不是结果。

I1,I2 I1,I3 I1,I4 I1,I5 I2,I3 I2,I4 I2,I5 I3,I4 I3,I5 I4,I5 
4     4     1     2     4     1     2     0     1     0

如果组合不在一个旁边,代码表示不匹配... 但这不是我需要的。

感谢您的帮助。真诚的

【问题讨论】:

  • 我可以,但是为了什么?

标签: r match sapply apriori


【解决方案1】:

此方法使用 reshape2 中使用的 melt.list 方法。从字符串拆分创建两个数据帧后,我们在字符串上合并并检查匹配组的数量。该代码是为搜索对量身定制的。如果长度发生变化,则必须在 len 处进行更改:

library(reshape2)
len <- 2
dfs <- lapply(list(result, a.new.list), 
               function(x) melt(strsplit(x, ",")))
m <- merge(dfs[[2]], dfs[[1]], by=1)
f <- function(n) sum(aggregate(value~L1.y, m[m$L1.x == n,], 
               function(x) length(unique(x)) == len )$value)
setNames(sapply(1:length(a.new.list), f), a.new.list)
#I1,I2 I1,I3 I1,I4 I1,I5 I2,I3 I2,I4 I2,I5 I3,I4 I3,I5 I4,I5 
#    4     4     1     2     4     2     2     0     1     0

数据

a.new.list <- scan(what="character", text='"I1,I2" "I1,I3" "I1,I4" "I1,I5" "I2,I3" "I2,I4" "I2,I5" "I3,I4" "I3,I5" "I4,I5"')
result <- scan(what="character", text=' "I1,I2,I5"    "I2,I4"       "I2,I3"      
 "I1,I2,I4"    "I1,I3"       "I2,I3"      
                "I1,I3"       "I1,I2,I3,I5" "I1,I2,I3"  ')

【讨论】:

    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 2020-08-17
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多