Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of unique values per row [duplicate]

Tags:

r

unique

count

row

I want to count the number of unique values per row.

For instance with this data frame:

example <- data.frame(var1 = c(2,3,3,2,4,5), 
                  var2 = c(2,3,5,4,2,5), 
                  var3 = c(3,3,4,3,4,5))

I want to add a column which counts the number of unique values per row; e.g. 2 for the first row (as there are 2's and 3's in the first row) and 1 for the second row (as there are only 3's in the second row).

Does anyone know an easy code to do this? Up until now I only found code for counting the number of unique values per column.

like image 292
VandenEnden Avatar asked Feb 20 '15 11:02

VandenEnden


People also ask

How do you count unique values without duplicates?

You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears.

How do I use Countif with unique?

In this case, you can use a combination of SUM, IF and COUNTIF functions to count unique values in Excel. To count unique values, enter the formula =SUM(IF(COUNTIF(range, range)=1,1,0)) in the desired cell. The range denotes the starting cell and the ending cell.


1 Answers

This apply function returns a vector of the number of unique values in each row:

apply(example, 1, function(x)length(unique(x)))

You can append it to your data.frame using on of the following two ways (and if you want to name that column as count):

example <- cbind(example, count = apply(example, 1, function(x)length(unique(x))))

or

example$count <- apply(example, 1, function(x)length(unique(x)))
like image 163
StrikeR Avatar answered Oct 02 '22 10:10

StrikeR