Dplyr: how to handle multiple values

I have a dataframe that returns 2 groups in the same min. How can it be processed to achieve the expected result?

df<- read.table(header=TRUE, text=" Company xxx yyyy zzzz cnt abc 1 1 1 20 aaa 1 1 2 3 bbb 1 1 1 3 ddd 2 0 2 100 ") 

I tried under the code

 final= df %>% group_by(xxx,yyyy) %>% summarise(Topcomp=Company[c(which(min(cnt)==cnt))]) 

Im getting:

Error: expecting a single value

I want to have an output as shown below.

  xxx yyyy Topcomp <int> <int> <fctr> 1 1 1 aaa,bbb 2 2 0 ddd 
+5
source share
2 answers

You can use paste(..., collapse = ",")

 df %>% group_by(xxx,yyyy) %>% summarise(Topcomp = paste(Company[min(cnt) == cnt], collapse = ",")) 
+5
source

You must do this:

 final= df %>% group_by(xxx,yyyy) %>% summarise(Topcomp=toString(Company[c(which(min(cnt)==cnt))])) ##Source: local data frame [2 x 3] ##Groups: xxx [?] ## ## xxx yyyy Topcomp ## <int> <int> <chr> ##1 1 1 aaa, bbb ##2 2 0 ddd 

You got an error because which returned two values ​​so that your subset of Company two values ​​when summarise requires one value. toString is similar to paste with collapse="," in that it collapses the two values ​​into a comma-separated string.

Also, as Alistair pointed out in his comment on another answer, you don't need c and which , so this can be simplified:

 final= df %>% group_by(xxx,yyyy) %>% summarise(Topcomp=toString(Company[min(cnt)==cnt])) 
+6
source

All Articles