Count unique values across columns in R

前端 未结 3 804
轻奢々
轻奢々 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:24

    Here is a method using tidyverse without looping

    library(tidyverse)
    df1 %>% 
       mutate(partners = str_c(names, partners, sep=", ")) %>%
       separate_rows(partners) %>%
       distinct %>% 
       count(names) %>% 
       right_join(df1)
    # A tibble: 4 x 3
    #  names       n partners                 
    #                          
    #1 John        4 Mary, Ashley, John, Kate 
    #2 Mary        3 Charlie, John, Mary, John
    #3 Charlie     3 Kate, Marcy              
    #4 David       3 Mary, Claire         
    

提交回复
热议问题