2014-11-21 22 views
0

我有一个列表,其中有1s和2s的不同长度向量,我试图根据nchar和标识,即1, 2, c(1,1), c(2,2), c(2,1), c(1,2)拉出向量。我的问题是确定包含组合c(1,1), c(2,2), c(2,1), c(1,2)nchar > 1的载体。多个数字的索引数字向量列表

#dummy code 

`T1,T2` <- 1 
`T2,T1` <- 2 
`T2,T3` <- c(2,1) 
`T3,T2` <- c(2,2) 
`T3,T4` <- c(1,1) 
`T4,T4` <- c(1,2) 
lst <- list(`T1,T2`=`T1,T2`, `T2,T1`=`T2,T1`, `T2,T3`=`T2,T3`, `T3,T2`=`T3,T2`, `T3,T4`=`T3,T4`, `T4,T4`=`T4,T4`) 

single <- lst[nchar(lst)==1] # only lists with nchar==1 
multiple <- lst[nchar(lst) > 1] # only lists with nchar > 1 

# identify single lists which contain 1s and 2s 
single_1s <- single[single==1] # single vectors for 1s 
single_2s <- single[single==2] # single vectors for 2s 

我该怎么做我的例子中的多个列表相同?

尝试识别包含任何组合c(1,1), c(2,2), c(2,1), c(1,2)的多个列表,例如,

multiple[multiple==c(1,1)] # Does not work 

任何指针将高度赞赏,感谢

+1

'多个[sapply(倍数,函数(x)的所有(x == C(1 ,1)))]' – akrun 2014-11-21 11:05:20

+0

整洁!十分感谢! – 2014-11-21 11:07:05

+0

是否需要列表中的所有匹配 – akrun 2014-11-21 11:07:32

回答

1

您可以创建所有那些需要进行匹配的矢量的list。然后使用lapply/sapply==到的indxlst每个元素与multiple

indxlst <- list(c(1,1), c(2,2), c(2,1), c(1,2)) 
lapply(indxlst, function(x) 
     multiple[sapply(multiple, function(y) all(y==x))]) 

匹配如果需要count

sapply(indxlst, function(x) sum(sapply(multiple, 
           function(y) all(y==x)))) 
+0

完美,非常感谢! :) – 2014-11-21 11:15:22