我如何计算每个子集中的数字?

时间:2014-12-30 03:51:10

标签: r frequency

我有几个这样的子集

s1 <- c(0,-1,0)  
s2 <- c(0,1,0) 
s3 <- c(0, 1, 2, 1, 2, 1, 2)

如果我想计算数字&#34; -4&#34;  例如

"-4"doesn't show up in s1 ,freq=0;

"-4"doesn't show up in s2 ,freq=0;

"-4"doesn't show up in s3 ,freq=0;

应该揭示频率= 0

代替

例如

"1"doesn't show up in s1 ,freq=0;

"1"does show up in s2 ,freq=1;

"1"does show up in s3 ,freq=2;

我能做些什么才能获得频率?

3 个答案:

答案 0 :(得分:1)

制作一个列表然后使用lapply

MyList <- list("s1"=s1, "s2"=s2, "s3"=s3)
lapply(MyList,function(x) length(x[x == -4])

结果是一个列表,每个列表元素的计数为-4

如果您想要一个计数向量而不是列表,可以将lapply替换为sapply,如果您想要总计数而不是每个元素数,这可能很有用。

答案 1 :(得分:1)

如果您有许多向量,并且不想手动将它们全部输入数据,您可以这样做:

lst <- mget(ls(pattern = "^s\\d+$"))   # to create a list of the vectors
sum(unlist(lst) == 4)
#[1] 0

答案 2 :(得分:1)

这显示了几种访问dots参数结果的方法:

 fn <- function(..., target)
  {  for ( i in seq_along( list(...) ) ){ 
        if( vl <- length( which( target == list(...)[[i]] ))){ 
               cat(target,"does show up in ") 
               objname <- deparse(substitute(list(...))[[i+1]])
               cat(objname,";length=",vl, "\n")
          } else{ 
              cat(target,"doesn't show up in ") 
              objname <- deparse(substitute(list(...))[[i+1]])
              cat(objname, "\n") }
     } }

 fn( s1,s2,s3, target=1)
1 doesn't show up in s1 
1 does show up in s2 ;length= 1 
1 does show up in s3 ;length= 3