每行计数唯一值 [英] Count number of unique values per row

查看:117
本文介绍了每行计数唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算每行的唯一值数量。



例如使用此数据框:

  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))

我想添加一个计数每行唯一值的数量的列;例如2为第一行(因为第一行有2和3),第二行为1(因为第二行只有3)。



有人知道一个简单的代码吗?到目前为止,我只找到用于计算每列唯一值的数量的代码。

解决方案

函数返回每行中唯一值数量的向量:

  ,function(x)length(unique(x)))



您可以将它附加到数据。框架使用以下两种方式(如果您要将该列命名为 count ):

 示例<  -  cbind(example,count = apply(example,1,function(x)length(unique(x))))
pre>

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


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.

解决方案

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)))

这篇关于每行计数唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆