Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique values in each of the columns of a data frame

Tags:

dataframe

r

I want to get the number of unique values in each of the columns of a data frame. Let's say I have the following data frame:

DF <- data.frame(v1 = c(1,2,3,2), v2 = c("a","a","b","b"))

then it should return that there are 3 distinct values for v1, and 2 for v2.

I tried unique(DF), but it does not work as each rows are different.

like image 304
Benoit_Plante Avatar asked Nov 04 '13 05:11

Benoit_Plante


People also ask

How do you find the unique values of a column in a data frame?

You can get unique values in column (multiple columns) from pandas DataFrame using unique() or Series. unique() functions. unique() from Series is used to get unique values from a single column and the other one is used to get from multiple columns.

How do I get unique values from multiple columns in a data frame?

Pandas series aka columns has a unique() method that filters out only unique values from a column. The first output shows only unique FirstNames. We can extend this method using pandas concat() method and concat all the desired columns into 1 single column and then find the unique of the resultant column.

What are unique values in a dataset?

Unique values are the distinct values that occur only once in the dataset or the first occurrences of duplicate values counted as unique values.

How do I get unique values from two data frames?

To get the unique values in multiple columns of a dataframe, we can merge the contents of those columns to create a single series object and then can call unique() function on that series object i.e. It returns the count of unique elements in multiple columns.


3 Answers

Or using unique:

rapply(DF,function(x)length(unique(x)))
v1 v2 
 3  2 
like image 183
agstudy Avatar answered Oct 10 '22 06:10

agstudy


sapply(DF, function(x) length(unique(x)))
like image 26
ben_says Avatar answered Oct 10 '22 05:10

ben_says


In dplyr:

DF %>% summarise_all(funs(n_distinct(.)))
like image 6
leerssej Avatar answered Oct 10 '22 07:10

leerssej