我有一个数字向量:
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值在向量中出现的次数?
我有一个数字向量:
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值在向量中出现的次数?
当前回答
下面是一种可以用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
其他回答
我可能会这样做
length(which(numbers==x))
但实际上,更好的方法是
table(numbers)
这里有一个快速而肮脏的方法:
x <- 23
length(subset(numbers, numbers==x))
你可以创建一个函数来得到结果。
# 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
这是一维原子向量的快速解。它依赖于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
在需要该输出的情况下,您甚至可能不需要它来重新返回原始向量,而第二列可能就是您所需要的全部。你可以用pipe在一行中得到:
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