计算R代码重复出现的次数
我需要一行代码来搜索数字向量并返回出现的次数。比如说计算R代码重复出现的次数,r,duplicates,R,Duplicates,我需要一行代码来搜索数字向量并返回出现的次数。比如说 a=c(15,32,27, 63, 15,99, 32,32) dup=unique(a[duplicated(V.Ints)]) len=length(unique(duplicated(dup))) 我得到: > dup #[1] 15, 32 > len #[1] 2 但我需要的是: > dup #[1] 15, 32 > len #[1] 5 谢谢大家! 您可以使用 table(a) # a # 1
a=c(15,32,27, 63, 15,99, 32,32)
dup=unique(a[duplicated(V.Ints)])
len=length(unique(duplicated(dup)))
我得到:
> dup
#[1] 15, 32
> len
#[1] 2
但我需要的是:
> dup
#[1] 15, 32
> len
#[1] 5
谢谢大家! 您可以使用
table(a)
# a
# 15 27 32 63 99
# 2 1 3 1 1
您可以筛选以仅查找重复项
Filter(function(x) x>1, table(a))
# a
# 15 32
# 2 3
names(Filter(function(x) x>1, table(a)))
# [1] "15" "32"
sum(Filter(function(x) x>1, table(a)))
# [1] 5
你可以求和,求出复制品的总长度
Filter(function(x) x>1, table(a))
# a
# 15 32
# 2 3
names(Filter(function(x) x>1, table(a)))
# [1] "15" "32"
sum(Filter(function(x) x>1, table(a)))
# [1] 5
阿伦在评论中的建议是未来的方向:
> sum(a %in% c(15,32))
#[1] 5
有关更一般的用法:
sum(a %in% unique(a[duplicated(a)]))
或者是一句符合弗利克方法精神的一句话:
sum(a %in% names(which(table(a) > 1)))
另一种变体是获取所有重复的值,然后对
leng
使用length()
,对dup使用unique()
x <- a[duplicated(a) | duplicated(a, fromLast=TRUE)]
length(x)
# [1] 5
unique(x)
# [1] 15 32
x