计算每行唯一值的数量 [英] Count number of unique values per row
问题描述
我想计算每行唯一值的数量.
I want to count the number of unique values per row.
例如使用这个数据框:
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).
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.
推荐答案
这个 apply
函数返回一个表示每行唯一值个数的向量:
This apply
function returns a vector of the number of unique values in each row:
apply(example, 1, function(x)length(unique(x)))
您可以使用以下两种方式之一将其附加到您的 data.frame 中(如果您想将该列命名为 count
):
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))))
或
example$count <- apply(example, 1, function(x)length(unique(x)))
这篇关于计算每行唯一值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!