[R] aggregate and list elements of variables in data.frame
Eik Vettorazzi
E@Vettor@zz| @end|ng |rom uke@de
Fri Jun 8 09:45:30 CEST 2018
Hi,
if you are willing to use dplyr, you can do all in one line of code:
library(dplyr)
df<-data.frame(id=1:10,A=c(123,345,123,678,345,123,789,345,123,789))
df%>%group_by(unique_A=A)%>%summarise(list_id=paste(id,collapse=", "))->r
cheers
Am 06.06.2018 um 10:13 schrieb Massimo Bressan:
> #given the following reproducible and simplified example
>
> t<-data.frame(id=1:10,A=c(123,345,123,678,345,123,789,345,123,789))
> t
>
> #I need to get the following result
>
> r<-data.frame(unique_A=c(123, 345, 678, 789),list_id=c('1,3,6,9','2,5,8','4','7,10'))
> r
>
> # i.e. aggregate over the variable "A" and list all elements of the variable "id" satisfying the criteria of having the same corrisponding value of "A"
> #any help for that?
>
> #so far I've just managed to "aggregate" and "count", like:
>
> library(sqldf)
> sqldf('select count(*) as count_id, A as unique_A from t group by A')
>
> library(dplyr)
> t%>%group_by(unique_A=A) %>% summarise(count_id = n())
>
> # thank you
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Eik Vettorazzi
Department of Medical Biometry and Epidemiology
University Medical Center Hamburg-Eppendorf
Martinistrasse 52
building W 34
20246 Hamburg
Phone: +49 (0) 40 7410 - 58243
Fax: +49 (0) 40 7410 - 57790
Web: www.uke.de/imbe
--
_____________________________________________________________________
Universitätsklinikum Hamburg-Eppendorf; Körperschaft des öffentlichen Rechts; Gerichtsstand: Hamburg | www.uke.de
Vorstandsmitglieder: Prof. Dr. Burkhard Göke (Vorsitzender), Prof. Dr. Dr. Uwe Koch-Gromus, Joachim Prölß, Martina Saurin (komm.)
_____________________________________________________________________
SAVE PAPER - THINK BEFORE PRINTING
More information about the R-help
mailing list