2016-06-11 7 views
0

指定した2つの列のgroupbyを実行し、それらのグループの行数をカウントし、どの行(ids)が属するかを格納したい各グループ。各グループに属しているレコードを特定する方法集計中に集計するR

以下は、すべてのトラックを維持するための適切な方法は何でしょう、COL1店舗の行ID場合はカウント

set.seed(1000) 
df <- data.frame(col1= sample(c(1:15), 15, replace = F), 
col2=sample(c("aa", "bb","cc"), 15, replace=TRUE), 
col3=sample(c('a','b','c','d'), 15, replace=TRUE, prob=c(0.25, 0.25, 0.20, 0.30))) 

View(df) 

enter image description here

grp<- df%>% 
group_by(col2, col3) %>% 
summarise(n=n()) 

enter image description here

をGROUPBYして得るために私を助け各グループに属するROWID?

+0

グループごとに行IDのリストを個別に表示しますか?いいえ、実際には名前をlistにしたい場合は、 'df [、1]'がすでに行IDを格納していて、 'df [、3]'と 'df [、2]'が明白であるならば、あなたはすでにこの情報を 'df '? –

+0

はい、必要条件:グループごとに行IDのリストを個別に作成する – andy

+0

再現可能な例を示してください。 –

答えて

2

あなたは今何をしているのか分かります。あなたは(DFから外すのように)、それは別のにする必要がある場合rowsByGrp<-grp$rowsちょうどその

library(dplyr) 
set.seed(1000) 
df <- data.frame(col1= sample(c(1:15), 15, replace = F), 
       col2=sample(c("aa", "bb","cc"), 15, replace=TRUE), 
       col3=sample(c('a','b','c','d'), 15, replace=TRUE, 
           prob=c(0.25, 0.25, 0.20, 0.30))) 


grp<-df %>% 
    group_by(col2, col3) %>% 
    summarise(n=n(), rows=paste(col1, collapse = ", ")) 
grp 

col2 col3  n    rows 
(fctr) (fctr) (int)    (chr) 
aa  b  6 5, 1, 15, 13, 8, 3 
aa  c  1     9 
bb  a  3   6, 12, 4 
bb  b  1     2 
bb  d  1     11 
cc  c  1     14 
cc  d  2    7, 10 

、あなたが必要しかし、そのベクトルを使用します。これを試してみてください。

rowsByGrp<-grp$rows 
rows.list<-lapply(1:length(rowsByGrp), function(x) rowsByGrp[x]) 
names(rows.list)<-paste(grp$col2 , grp$col3, sep = "_") 
rows.list 

    $aa_b 
[1] "5, 1, 15, 13, 8, 3" 

$aa_c 
[1] "9" 

$bb_a 
[1] "6, 12, 4" 

$bb_b 
[1] "2" 

$bb_d 
[1] "11" 

$cc_c 
[1] "14" 

$cc_d 
[1] "7, 10" 
+0

ありがとうBryan :) – andy

関連する問題