List distinct values in a vector in R

RVectorDistinct ValuesR Faq

R Problem Overview


How can I list the distinct values in a vector where the values are replicative? I mean, similarly to the following SQL statement:

SELECT DISTINCT product_code
FROM data

R Solutions


Solution 1 - R

Do you mean unique:

R> x = c(1,1,2,3,4,4,4)
R> x
[1] 1 1 2 3 4 4 4
R> unique(x)
[1] 1 2 3 4

Solution 2 - R

If the data is actually a factor then you can use the levels() function, e.g.

levels( data$product_code )

If it's not a factor, but it should be, you can convert it to factor first by using the factor() function, e.g.

levels( factor( data$product_code ) )

Another option, as mentioned above, is the unique() function:

unique( data$product_code )

The main difference between the two (when applied to a factor) is that levels will return a character vector in the order of levels, including any levels that are coded but do not occur. unique will return a factor in the order the values first appear, with any non-occurring levels omitted (though still included in levels of the returned factor).

Solution 3 - R

Try using the duplicated function in combination with the negation operator "!".

Example:

wdups <- rep(1:5,5)
wodups <- wdups[which(!duplicated(wdups))]

Hope that helps.

Solution 4 - R

You can also use the sqldf package in R.

Z <- sqldf('SELECT DISTINCT tablename.columnname FROM tablename ')

Solution 5 - R

another way would be to use dplyr package:

x = c(1,1,2,3,4,4,4)
dplyr::distinct(as.data.frame(x))

Solution 6 - R

In R Language (version 3.0+) You can apply filter to get unique out of a list-

data.list <- data.list %>% unique

or couple it with other operation as well

data.list.rollnumbers <- data.list %>% pull(RollNumber) %>% unique

unique doesn't require dplyr.

Solution 7 - R

this may work as well,

1) unlist(lapply(mtcars, function(x) length(unique(x))))
2) lapply(mtcars, function(x) unique(x))

outcomes,

  1. mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
     25    3   27   22   22   29   30    2    2    3    6 
    
  2. $mpg
    [1] 21.0 22.8 21.4 18.7 18.1 14.3 24.4 19.2 17.8 16.4 17.3 15.2 10.4 14.7 32.4 30.4 33.9 21.5 15.5 13.3 27.3 26.0 15.8 19.7 15.0
    $cyl
    [1] 6 4 8
    $ and so on....
    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMehper C. PalavuzlarView Question on Stackoverflow
Solution 1 - RcsgillespieView Answer on Stackoverflow
Solution 2 - RisapirView Answer on Stackoverflow
Solution 3 - RAl R.View Answer on Stackoverflow
Solution 4 - RClay BurnsView Answer on Stackoverflow
Solution 5 - RAlexBView Answer on Stackoverflow
Solution 6 - RVishal Kumar SahuView Answer on Stackoverflow
Solution 7 - RSeyma KalayView Answer on Stackoverflow