[R] aggregate and list elements of variables in data.frame
    Massimo Bressan 
    m@@@|mo@bre@@@n @end|ng |rom @rp@@veneto@|t
       
    Thu Jun  7 15:27:56 CEST 2018
    
    
  
thank you for the help 
this is my solution based on your valuable hint but without the need to pass through the use of a 'tibble' 
x<-data.frame(id=LETTERS[1:10], A=c(123,345,123,678,345,123,789,345,123,789)) 
uA<-unique(x$A) 
idx<-lapply(uA, function(v) which(x$A %in% v)) 
vals<- lapply(idx, function(index) x$id[index]) 
data.frame(unique_A = uA, list_vals=unlist(lapply(vals, paste, collapse = ", "))) 
best 
Da: "Ben Tupper" <btupper using bigelow.org> 
A: "Massimo Bressan" <massimo.bressan using arpa.veneto.it> 
Cc: "r-help" <R-help using r-project.org> 
Inviato: Giovedì, 7 giugno 2018 14:47:55 
Oggetto: Re: [R] aggregate and list elements of variables in data.frame 
Hi, 
Does this do what you want? I had to change the id values to something more obvious. It uses tibbles which allow each variable to be a list. 
library(tibble) 
library(dplyr) 
x <- tibble(id=LETTERS[1:10], 
A=c(123,345,123,678,345,123,789,345,123,789)) 
uA <- unique(x$A) 
idx <- lapply(uA, function(v) which(x$A %in% v)) 
vals <- lapply(idx, function(index) x$id[index]) 
r <- tibble(unique_A = uA, list_idx = idx, list_vals = vals) 
> r 
# A tibble: 4 x 3 
unique_A list_idx list_vals 
<dbl> <list> <list> 
1 123. <int [4]> <chr [4]> 
2 345. <int [3]> <chr [3]> 
3 678. <int [1]> <chr [1]> 
4 789. <int [2]> <chr [2]> 
> r$list_idx[1] 
[[1]] 
[1] 1 3 6 9 
> r$list_vals[1] 
[[1]] 
[1] "A" "C" "F" "I" 
Cheers, 
ben 
	[[alternative HTML version deleted]]
    
    
More information about the R-help
mailing list