计算每一列的唯一值
问题描述:
我想返回表中每一列的唯一值的计数。例如,如果我有表:
I would like to return the count of the unique values for every column in a table. For example, if I have the table:
Testdata <- data.frame(var_1 = c("a","a","a"), var_2 = c("b","b","b"), var_3 = c("c","d","e"))
var_1 | var_2 | var_3
a | b | c
a | b | d
a | b | e
我希望输出为:
Variable | Unique_Values
var_1 | 1
var_2 | 1
var_3 | 3
我尝试使用唯一功能来处理循环,例如
I have tried playing around with loops using the unique function, e.g.
for(i in names(Testdata)){
# Code using unique function
}
但是我怀疑有更简单的方法。
However I suspect there is a simpler way.
答
您可以使用 apply
:
apply(Testdata, 2, function(x) length(unique(x)))
# var_1 var_2 var_3
# 1 1 3