0

I have thise code that generates random values as part of a sequence. I need to keep duplicates and remove values that are NOT repeated. Any help with this?

Apparently, a solution is supposed to contain '%/%, as.numeric, names, table, >'

Here is original code.

x <- sample(c(-10:10), sample(20:40, 1), replace = TRUE)

Any help would be appreciated!

lo440251
  • 3
  • 4
  • This sounds like homework. I answered because I have assumed you are not doing this for grades but if that is the case stack overflow is not for this and eventually your account will be banned. – Angus Campbell May 22 '22 at 23:19
  • Sorry about that. Thanks for your help, won't do it again. Apologies. – lo440251 May 23 '22 at 00:27

1 Answers1

0

I would use table(). Table will give you a list of all values and the number of times they occur.

    vec <- c(1,2,3,4,5,3,4,5,4,5)
    
valueset <- unique(vec) # all unique values in vec, will be used later
#now we determine whihc values are occuring more than once
    valuecounts <- table(vec) # returns count of all unique values, values are in the names of this variable as strings now regardless of original data type
    morethanone <- names(valuecounts)[valuecounts>1] #returns values with count>1
    morethanone <- as.numeric(morethanone) # converts strings back to numeric
    valueset[valueset %in% morethanone] #returns the original values which passed the above cirteria

As a function....

duplicates <- function(vector){
# Returns all unique values that occur more than once in a list
    valueset <- unique(vector) 
    valuecounts <- table(vector)
    morethanone <- names(valuecounts)[valuecounts>1]
    morethanone <- as.numeric(morethanone)
    return( valueset[valueset %in% morethanone] ) 
}

Now try running duplicates(x)

Angus Campbell
  • 563
  • 4
  • 19