programing

벡터에서 x 값을 사용하여 요소 수

cafebook 2023. 7. 7. 21:07
반응형

벡터에서 x 값을 사용하여 요소 수

나는 다음과 같은 수의 벡터를 가지고 있습니다.

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
         453,435,324,34,456,56,567,65,34,435)

어떻게 하면 R이 벡터에 x 값이 나타나는 횟수를 세게 할 수 있습니까?

그냥 사용할 수 있습니다.table():

> a <- table(numbers)
> a
numbers
  4   5  23  34  43  54  56  65  67 324 435 453 456 567 657 
  2   1   2   2   1   1   2   1   2   1   3   1   1   1   1 

그런 다음 하위 집합을 지정할 수 있습니다.

> a[names(a)==435]
435 
  3

또는 다음과 같이 작업하는 것이 더 편하다면 data.frame으로 변환합니다.

> as.data.frame(table(numbers))
   numbers Freq
1        4    2
2        5    1
3       23    2
4       34    2
...

은 가장직적방법은입니다.sum(numbers == x).

numbers == x하며, x가 발생할 때 TRUE인 논리 벡터를 생성합니다.sum로, 를 0ing으로 로 강제 됩니다.

는 다음과 같은sum(abs(numbers - x) < 1e-6).

저는 아마 이런 일을 할 것입니다.

length(which(numbers==x))

하지만 정말로, 더 좋은 방법은

table(numbers)

▁is도 있습니다.count(numbers)plyr꾸미훨편보다 훨씬 합니다.table내 생각으로는

은 내가선솔루은션을 합니다.rle 값을반라다니합환벨라(,x이 예제에서는)와 해당 값이 순서대로 나타나는 횟수를 나타내는 길이를 나타냅니다.

조하여합을 으로써.rle와 함께sort값이 표시된 횟수를 매우 빠르게 셀 수 있습니다.이것은 더 복잡한 문제에 도움이 될 수 있습니다.

예:

> numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,453,435,324,34,456,56,567,65,34,435)
> a <- rle(sort(numbers))
> a
  Run Length Encoding
    lengths: int [1:15] 2 1 2 2 1 1 2 1 2 1 ...
    values : num [1:15] 4 5 23 34 43 54 56 65 67 324 ...

원하는 값이 표시되지 않거나 나중에 사용할 수 있도록 해당 값을 저장해야 하는 경우a a data.frame.

> b <- data.frame(number=a$values, n=a$lengths)
> b
    values n
 1       4 2
 2       5 1
 3      23 2
 4      34 2
 5      43 1
 6      54 1
 7      56 2
 8      65 1
 9      67 2
 10    324 1
 11    435 3
 12    453 1
 13    456 1
 14    567 1
 15    657 1

모든 값이 아닌 한 값의 빈도를 알고 싶어하는 경우는 드물고, rle이 모든 값을 세고 저장하는 가장 빠른 방법인 것 같습니다.

R에는 그것에 대한 표준 함수가 있습니다.

tabulate(numbers)

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435 453,435,324,34,456,56,567,65,34,435)

> length(grep(435, numbers))
[1] 3


> length(which(435 == numbers))
[1] 3


> require(plyr)
> df = count(numbers)
> df[df$x == 435, ] 
     x freq
11 435    3


> sum(435 == numbers)
[1] 3


> sum(grepl(435, numbers))
[1] 3


> sum(435 == numbers)
[1] 3


> tabulate(numbers)[435]
[1] 3


> table(numbers)['435']
435 
  3 


> length(subset(numbers, numbers=='435')) 
[1] 3

출연 횟수를 나중에 세고 싶다면 다음을 사용할 수 있습니다.sapply함수:

index<-sapply(1:length(numbers),function(x)sum(numbers[1:x]==numbers[x]))
cbind(numbers, index)

출력:

        numbers index
 [1,]       4     1
 [2,]      23     1
 [3,]       4     2
 [4,]      23     2
 [5,]       5     1
 [6,]      43     1
 [7,]      54     1
 [8,]      56     1
 [9,]     657     1
[10,]      67     1
[11,]      67     2
[12,]     435     1
[13,]     453     1
[14,]     435     2
[15,]     324     1
[16,]      34     1
[17,]     456     1
[18,]      56     2
[19,]     567     1
[20,]      65     1
[21,]      34     2
[22,]     435     3

빠르고 더러운 한 가지 방법이 있습니다.

x <- 23
length(subset(numbers, numbers==x))

다음 줄에서 원하는 대로 번호를 변경할 수 있습니다.

length(which(numbers == 4))

한 은 한가방다같습다니음과은법지다를 사용하는 일 수 .vec_count()vctrs라이브러리:

vec_count(numbers)

   key count
1  435     3
2   67     2
3    4     2
4   34     2
5   56     2
6   23     2
7  456     1
8   43     1
9  453     1
10   5     1
11 657     1
12 324     1
13  54     1
14 567     1
15  65     1

기본 순서는 가장 빈도가 높은 값을 맨 위에 배치합니다.하는 경우(a 따정경우는하렬라키에a(a))table()- 출력 like 출력):

vec_count(numbers, sort = "key")

   key count
1    4     2
2    5     1
3   23     2
4   34     2
5   43     1
6   54     1
7   56     2
8   65     1
9   67     2
10 324     1
11 435     3
12 453     1
13 456     1
14 567     1
15 657     1

제가 편리하다고 생각하는 또 다른 방법은 다음과 같습니다.

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,453,435,324,34,456,56,567,65,34,435)
(s<-summary (as.factor(numbers)))

그러면 데이터 집합이 요인으로 변환되고 요약()이 관리 합계(고유 값 카운트)를 제공합니다.

출력:

4   5  23  34  43  54  56  65  67 324 435 453 456 567 657 
2   1   2   2   1   1   2   1   2   1   3   1   1   1   1 

원하는 경우 데이터 프레임으로 저장할 수 있습니다.

as.data.frame(cbind(숫자 = 이름), Freq = s), stringAsFactors=F, row.names = 1: 길이)

여기서 row.name은 행 이름을 변경하는 데 사용되었습니다.s의 열 이름은 row.names를 사용하지 않고 새 데이터 프레임에서 행 이름으로 사용됩니다.

출력:

     Number Freq
1       4    2
2       5    1
3      23    2
4      34    2
5      43    1
6      54    1
7      56    2
8      65    1
9      67    2
10    324    1
11    435    3
12    453    1
13    456    1
14    567    1
15    657    1

표를 사용하지만 비교하지 않음names:

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435)
x <- 67
numbertable <- table(numbers)
numbertable[as.character(x)]
#67 
# 2 

table여러 요소의 카운트를 여러 번 사용할 때 유용합니다.카운트가 하나만 필요한 경우sum(numbers == x)

특정 요소를 세는 데는 여러 가지 방법이 있습니다.

library(plyr)
numbers =c(4,23,4,23,5,43,54,56,657,67,67,435,453,435,7,65,34,435)

print(length(which(numbers==435)))

#Sum counts number of TRUE's in a vector 
print(sum(numbers==435))
print(sum(c(TRUE, FALSE, TRUE)))

#count is present in plyr library 
#o/p of count is a DataFrame, freq is 1 of the columns of data frame
print(count(numbers[numbers==435]))
print(count(numbers[numbers==435])[['freq']])

이것은 1차원 원자 벡터에 대한 매우 빠른 해결책입니다.에 의존합니다.match()그래서 그것은 호환됩니다.NA:

x <- c("a", NA, "a", "c", "a", "b", NA, "c")

fn <- function(x) {
  u <- unique.default(x)
  out <- list(x = u, freq = .Internal(tabulate(match(x, u), length(u))))
  class(out) <- "data.frame"
  attr(out, "row.names") <- seq_along(u)
  out
}

fn(x)

#>      x freq
#> 1    a    3
#> 2 <NA>    2
#> 3    c    2
#> 4    b    1

알고리즘이 실행되지 않도록 조정할 수도 있습니다.unique().

fn2 <- function(x) {
  y <- match(x, x)
  out <- list(x = x, freq = .Internal(tabulate(y, length(x)))[y])
  class(out) <- "data.frame"
  attr(out, "row.names") <- seq_along(x)
  out
}

fn2(x)

#>      x freq
#> 1    a    3
#> 2 <NA>    2
#> 3    a    3
#> 4    c    2
#> 5    a    3
#> 6    b    1
#> 7 <NA>    2
#> 8    c    2

출력이 바람직한 경우 원래 벡터를 다시 반환하는 데 필요하지 않을 수 있으며 두 번째 열만 있으면 됩니다.파이프와 한 줄로 연결할 수 있습니다.

match(x, x) %>% `[`(tabulate(.), .)

#> [1] 3 2 3 2 3 1 2 2

2021년 기본 솔루션

aggregate(numbers, list(num=numbers), length)

       num x
1        4 2
2        5 1
3       23 2
4       34 2
5       43 1
6       54 1
7       56 2
8       65 1
9       67 2
10     324 1
11     435 3
12     453 1
13     456 1
14     567 1
15     657 1

tapply(numbers, numbers, length)
  4   5  23  34  43  54  56  65  67 324 435 453 456 567 657 
  2   1   2   2   1   1   2   1   2   1   3   1   1   1   1 

by(numbers, list(num=numbers), length)
num: 4
[1] 2
-------------------------------------- 
num: 5
[1] 1
-------------------------------------- 
num: 23
[1] 2
-------------------------------------- 
num: 34
[1] 2
-------------------------------------- 
num: 43
[1] 1
-------------------------------------- 
num: 54
[1] 1
-------------------------------------- 
num: 56
[1] 2
-------------------------------------- 
num: 65
[1] 1
-------------------------------------- 
num: 67
[1] 2
-------------------------------------- 
num: 324
[1] 1
-------------------------------------- 
num: 435
[1] 3
-------------------------------------- 
num: 453
[1] 1
-------------------------------------- 
num: 456
[1] 1
-------------------------------------- 
num: 567
[1] 1
-------------------------------------- 
num: 657
[1] 1

이 작업은 다음을 통해 수행할 수 있습니다.outer동등성의 메트릭과 그 다음을 구합니다.rowSums명백한 의미로
카운트를 얻기 위해서 그리고.numbers동일한 데이터 집합에서 data.frame이 먼저 생성됩니다.별도의 입력과 출력을 원하는 경우에는 이 단계가 필요하지 않습니다.

df <- data.frame(No = numbers)
df$count <- rowSums(outer(df$No, df$No, FUN = `==`))

긴 벡터에서 비교적 빠르고 편리한 출력을 제공하는 방법은 다음과 같습니다.lengths(split(numbers, numbers))(끝에 S 표시)lengths):

# Make some integer vectors of different sizes
set.seed(123)
x <- sample.int(1e3, 1e4, replace = TRUE)
xl <- sample.int(1e3, 1e6, replace = TRUE)
xxl <-sample.int(1e3, 1e7, replace = TRUE)

# Number of times each value appears in x:
a <- lengths(split(x,x))

# Number of times the value 64 appears:
a["64"]
#~ 64
#~ 15

# Occurences of the first 10 values
a[1:10]
#~ 1  2  3  4  5  6  7  8  9 10 
#~ 13 12  6 14 12  5 13 14 11 14 

출력은 단순히 명명된 벡터입니다.
속도는 다음과 유사한 것으로 표시됩니다.rle제이베커가 제안했고 매우 긴 벡터에서 조금 더 빠릅니다.다음은 R 3.6.2의 마이크로 벤치마크이며, 일부 기능이 제안되었습니다.

library(microbenchmark)

f1 <- function(vec) lengths(split(vec,vec))
f2 <- function(vec) table(vec)
f3 <- function(vec) rle(sort(vec))
f4 <- function(vec) plyr::count(vec)

microbenchmark(split = f1(x),
               table = f2(x),
               rle = f3(x),
               plyr = f4(x))
#~ Unit: microseconds
#~   expr      min        lq      mean    median        uq      max neval  cld
#~  split  402.024  423.2445  492.3400  446.7695  484.3560 2970.107   100  b  
#~  table 1234.888 1290.0150 1378.8902 1333.2445 1382.2005 3203.332   100    d
#~    rle  227.685  238.3845  264.2269  245.7935  279.5435  378.514   100 a   
#~   plyr  758.866  793.0020  866.9325  843.2290  894.5620 2346.407   100   c 

microbenchmark(split = f1(xl),
               table = f2(xl),
               rle = f3(xl),
               plyr = f4(xl))
#~ Unit: milliseconds
#~   expr       min        lq      mean    median        uq       max neval cld
#~  split  21.96075  22.42355  26.39247  23.24847  24.60674  82.88853   100 ab 
#~  table 100.30543 104.05397 111.62963 105.54308 110.28732 168.27695   100   c
#~    rle  19.07365  20.64686  23.71367  21.30467  23.22815  78.67523   100 a  
#~   plyr  24.33968  25.21049  29.71205  26.50363  27.75960  92.02273   100  b 

microbenchmark(split = f1(xxl),
               table = f2(xxl),
               rle = f3(xxl),
               plyr = f4(xxl))
#~ Unit: milliseconds
#~   expr       min        lq      mean    median        uq       max neval  cld
#~  split  296.4496  310.9702  342.6766  332.5098  374.6485  421.1348   100 a   
#~  table 1151.4551 1239.9688 1283.8998 1288.0994 1323.1833 1385.3040   100    d
#~    rle  399.9442  430.8396  464.2605  471.4376  483.2439  555.9278   100   c 
#~   plyr  350.0607  373.1603  414.3596  425.1436  437.8395  506.0169   100  b  

중요한 것은 결측값의 수를 계산하는 유일한 함수입니다.NA이라plyr::count이들은 다음을 사용하여 별도로 얻을 수도 있습니다.sum(is.na(vec))

다음은 dplyr로 수행할 수 있는 방법입니다.

library(tidyverse)

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
             453,435,324,34,456,56,567,65,34,435)
ord <- seq(1:(length(numbers)))

df <- data.frame(ord,numbers)

df <- df %>%
  count(numbers)

numbers     n
     <dbl> <int>
 1       4     2
 2       5     1
 3      23     2
 4      34     2
 5      43     1
 6      54     1
 7      56     2
 8      65     1
 9      67     2
10     324     1
11     435     3
12     453     1
13     456     1
14     567     1
15     657     1

당신은 당신에게 결과를 제공하는 기능을 만들 수 있습니다.

# your list
numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
         453,435,324,34,456,56,567,65,34,435)

function1<-function(x){
    if(x==value){return(1)}else{ return(0) }
}

# set your value here
value<-4

# make a vector which return 1 if it equal to your value, 0 else
vector<-sapply(numbers,function(x) function1(x))
sum(vector)

결과: 2

언급URL : https://stackoverflow.com/questions/1923273/counting-the-number-of-elements-with-the-values-of-x-in-a-vector

반응형