Count unique values for every column

前端 未结 8 1065
眼角桃花
眼角桃花 2020-12-05 14:13

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         


        
相关标签:
8条回答
  • 2020-12-05 15:05

    You could use apply:

    apply(Testdata, 2, function(x) length(unique(x)))
    # var_1 var_2 var_3 
    #     1     1     3
    
    0 讨论(0)
  • 2020-12-05 15:07

    Here's an alternative:

    aggregate(values ~ ind, unique(stack(Testdata)), length)
    #     ind values
    # 1 var_1      1
    # 2 var_2      1
    # 3 var_3      3
    

    This requires the columns be character.

    0 讨论(0)
提交回复
热议问题