Count unique values across columns in R

前端 未结 3 805
轻奢々
轻奢々 2021-01-27 00:42

I am trying to create a new variable with unique counts of string values from two different columns. So I have something like this, for example:

# A tibble: 4 x         


        
3条回答
  •  被撕碎了的回忆
    2021-01-27 01:35

    There's another way with toString.

    dat$uniquecounts <- sapply(strsplit(apply(dat, 1, toString), ", "), 
                               function(x) length(unique(x)))
    
    dat
    #     names                  partners uniquecounts
    # 1    John  Mary, Ashley, John, Kate            4
    # 2    Mary Charlie, John, Mary, John            3
    # 3 Charlie               Kate, Marcy            3
    # 4   David              Mary, Claire            3
    

提交回复
热议问题