Identify and count repeated elements in a vector

Viewed 24

I want to create a function such that, given a vector V, it outputs a matrix with columns: the first containing all those elements who are repeated in the vector; and the second specifying how many times that repeated value appears (if it is repeated only once, it should say 2, and so on.).

I've come up with the following code, which can correctly identify the repeated values in the vector, but I don't know how to add the second part: specify how many times that value appears.

Repetidos <- function(V){
  Resultado <- matrix(nrow = 10, ncol = 2)
  n <- 0
  for(i in 1:(length(V) - 1)){
    for(j in (i + 1):length(V)){
      if(V[i] == V[j]){
        n <- n + 1
        Resultado[n, 1] <- V[i]
        Resultado[n, 2] <- n
      }
    }
  }
  return(Resultado)
}

V <- c(1, 1, 2, 2, 3, 3, 4, 5, 5)
Repetidos(V)

> Repetidos(V)
      [,1] [,2]
 [1,]    1    1
 [2,]    2    2
 [3,]    3    3
 [4,]    5    4
 [5,]   NA   NA
 [6,]   NA   NA
 [7,]   NA   NA
 [8,]   NA   NA
 [9,]   NA   NA
[10,]   NA   NA
0 Answers
Related