2017-04-17 65 views
2

我想运行函数,将采取一个参数,这是数字列表,并计数重复。计数重复值的数量

实施例:

number <- c(1, 1, 1, 2, 2, 4, 5) 

在这种情况下,输出将是2,因为只有1和2具有重复。

我知道如何使用for循环,但不知道如何计数重复。

count = 0 
for (x in number){ 
    ... 
} 
+2

或'sum(table(x)> 1)' –

回答

4

将这些值制成表格,然后计算其中有多少个值大于1。

x <- c(1, 1, 1, 2, 2, 4, 5) 

sum(tabulate(x) > 1) 
# [1] 2 

或者,如果你正在寻找重复的直管段,rle可以作为替代列表。

with(rle(x), sum(lengths > 1)) 
# [1] 2 
0

该解决方案写在Python

import collections 
number = [1,1,1,2,2,4,5] 
x = collections.Counter(number) 
len([i for i in x if x[i]>1]) 

它将数字出现在列表中多次,然后计算该列表中有多少个元素。

+2

问题标记为R,而不是Python。 –