List distinct values in a vector in R

2019-02-01 20:03发布

问题:

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

回答1:

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


回答2:

You can also use the sqldf package in R. Z <-sqldf('SELECT DISTINCT tablename.columnname FROM tablename ')



回答3:

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.



回答4:

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 )