计算出现次数

时间:2017-02-26 15:04:12

标签: r

我有以下问题。我想计算小于或等于零的值的出现次数。在以下数据中的示例我有3次出现1(0,0,0),2(-1,-2),3(0,0)。 R中是否有任何函数构建来计算连续出现的次数。

a <- c(2,4,5,3,2,4,7,0,0,0,4,3,2,-1,-2,3,2,0,0,4)

5 个答案:

答案 0 :(得分:6)

如果要计算值低于零的运行次数:

sum(rle(a <= 0)$values)

给出:

[1] 3

这是如何运作的:

  • 使用rle功能,您可以创建一个a <= 0的运行长度编码。
  • rle(a <= 0)的输出为:

    Run Length Encoding
      lengths: int [1:7] 7 3 3 2 2 2 1
      values : logi [1:7] FALSE TRUE FALSE TRUE FALSE TRUE ...
    
  • 现在您只需要对rle - 对象的值部分求和:

    > sum(rle(a <= 0)$values)
    [1] 3
    

答案 1 :(得分:5)

您可以使用rle

> sum(rle(a<=0)$values)
[1] 3

说明:

rle将向量分解为&gt; 0或&lt; = 0. $valuestruefalse,取决于相应的运行是否满足谓词(a <= 0)或其否定。您希望对应于值TRUE的运行,函数sum将这些TRUE强制为1。

答案 2 :(得分:1)

这是使用<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On # Redirect Trailing Slashes... RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule>

的另一个选项(不重复相同的内容)
rleid

library(data.table) uniqueN(rleid(a<=0)[a<=0]) #[1] 3 给出逻辑向量的运行长度id(rleid),使用逻辑向量(a <=0)对id进行子集并找到[a<=0]使用length

unique ID

uniqueN方法

base R

答案 3 :(得分:1)

使用rle接受的答案很好,但这是另一种方法:

b <- a <= 0
sum(b) - sum(b[which(b) - 1])

这会计算非正元素的数量,并减去其中有多少元素在非正元素之前的数量(因此每次非正数运行的开始只会产生贡献。)

我做了一个快速测试,发现对于大型载体(1000万到3亿个元素),运行速度要快几倍。

v1 <- function(a) sum(rle(a<=0)$values)

v2 <- function(a) {
  b <- a <= 0
  sum(b) - sum(b[which(b) - 1])
}

v1.time <- NULL
v2.time <- NULL
sizes <- 1:30 * 1E7
for (s in sizes) {
  x <- sample(-100:100, s, replace = TRUE)

  v1.time <- c(v1.time, system.time(
    v1.result <- v1(x)
  )[['elapsed']])

  v2.time <- c(v2.time, system.time(
    v2.result <- v2(x)
  )[['elapsed']])

  print(c(v1.result, v2.result)) # Show that they agree
  print(v1.time)
  print(v2.time)
}

library(tidyverse)
data.frame(VectorSize = sizes,
           v1 = v1.time,
           v2 = v2.time) %>%
  gather('Version', 'Time', -VectorSize) %>%
  ggplot(aes(x = VectorSize, y = Time, color = Version)) + geom_point() + geom_smooth()

enter image description here

答案 4 :(得分:0)

在此示例中,如何计算所有复制中的所有事件?

set.seed(3)
b<-c(4,6,4,2,3)
run<- replicate(2,{
a <- runif(5,3,5)
dif <- a - b
return(dif)
})
run
 [,1]       [,2]
[1,] -0.6639169  0.2087881
[2,] -1.3849672 -2.7507331
[3,] -0.2301153 -0.4107982
[4,]  1.6554686  2.1552198
[5,]  1.2042013  1.2619585

当我尝试

sum(rle(run<=0)$values)

我得到了

Error in rle(run <= 0) : 'x' must be a vector of an atomic type

但它正在使用

uniqueN(rleid(run<=0)[run<=0])