2016-06-21 5 views
1

小さな文字ベクトルの値を表にし、その文字列に表の結果を追加したいと思います。以下、再現例えば、私の所望の出力は次のようになります。R - 文字ベクトルの表を作成する - カスタマイズされた出力

states     responsible 
1  KS    Joe(2);Suzie(3) 
2  MO      Bob(4) 
3  CO Suzie(1);Bob(2);Ralph(3) 
4  NE      Joe(1) 
5  MT   Suzie(3);Ralph(1) 

をここでは例のデータがあります:

states <- c("KS", "MO", "CO", "NE", "MT") 
responsible <- list(c("Joe", "Joe", "Suzie", "Suzie", "Suzie"), c("Bob", "Bob", "Bob", "Bob"), c("Suzie", "Bob", "Ralph", "Ralph", "Bob", "Ralph"), "Joe", c("Suzie", "Ralph", "Suzie", "Suzie")) 

df <- as.data.frame(cbind(states, responsible)) 

#Tabulating using table() 
resp.tab <- lapply(responsible, table) 

#Is there a way I can do tabulation without converting to factors? 
# OR 
#Is there a way to access the factor label and value, then paste them together? 
+0

'です。 – akrun

答えて

2

我々はdata.tableを使用することができます。 'responsible'のlengthsと 'responsible'のを複製してdata.tableを作成します。 「状態」、および「責任」によってグループ化された

library(data.table) 
dt1 <- data.table(states= rep(states, lengths(responsible)), 
       responsible=unlist(responsible)) 

、我々はその後、「状態」によってグループ化され、周波​​数(.N)を取得し、私たちは「責任」をpasteと「N」列とcollapse行が属します同じ '状態'。

dt1[, .N, .(states, responsible) 
    ][, .(responsible = paste(paste0(responsible, 
        "(", N, ")"), collapse=";")) ,.(states)] 
# states    responsible 
#1:  KS   Joe(2);Suzie(3) 
#2:  MO     Bob(4) 
#3:  CO Suzie(1);Bob(2);Ralph(3) 
#4:  NE     Joe(1) 
#5:  MT  Suzie(3);Ralph(1) 

または類似のオプションもcharacter`ベクトル `と連携table` dplyr/tidyr

library(dplyr) 
library(tidyr) 
tbl_df(dt1) %>% 
    group_by(states, responsible) %>% 
    tally() %>% 
    unite(responsible, responsible, n, sep="(") %>% 
    group_by(states) %>% 
    summarise(responsible = paste(paste0(responsible, ")"), collapse=";")) 
関連する問題