2017-09-06 57 views
1

我有一個列表「cluster_features」,這裏是什麼樣子:寫列表的數據幀,然後CSV但2列

> cluster_features[1:3] 
$cluster1 
      dui  control   physic  dui_physic physic_control  alcohol 
     281673   10759   10756   10756   10756   2917 

$cluster2 
     investig    auto  investig_auto    death death_investig   non-crim 
      41964    17445    17445    2815    2815    920 
investig_non-crim    fire  fire_investig 
       920    580    503 

$cluster3 
     assist   agenc agenc_assist assist_other   public  motorist motorist_assist 
      98605   29118   18968   16655   16107   10261   8354 
      fire assist_public   servic public_assist   call   general general_assist 
      7047   6952   6105   5679   5642   5630   5306 
    servic_call    cad  assist_fire   escort assist_escort escort_servic 
      5303   5259   4965   4954   4954   4954 

生成方式:

dput(cluster_features[1:3]) 
structure(list(cluster1 = structure(c(281673, 10759, 10756, 10756, 
10756, 2917), .Names = c("dui", "control", "physic", "dui_physic", 
"physic_control", "alcohol")), cluster2 = structure(c(41964, 
17445, 17445, 2815, 2815, 920, 920, 580, 503), .Names = c("investig", 
"auto", "investig_auto", "death", "death_investig", "non-crim", 
"investig_non-crim", "fire", "fire_investig")), cluster3 = structure(c(98605, 
29118, 18968, 16655, 16107, 10261, 8354, 7047, 6952, 6105, 5679, 
5642, 5630, 5306, 5303, 5259, 4965, 4954, 4954, 4954), .Names = c("assist", 
"agenc", "agenc_assist", "assist_other", "public", "motorist", 
"motorist_assist", "fire", "assist_public", "servic", "public_assist", 
"call", "general", "general_assist", "servic_call", "cad", "assist_fire", 
"escort", "assist_escort", "escort_servic"))), .Names = c("cluster1", 
"cluster2", "cluster3")) 

我的目標是以類似的格式將數據導出到csv。也就是說,可能columnA是key,然後是列b的所有鍵的值。所以它看起來像這樣的: enter image description here

我嘗試這樣做:

x <- do.call("rbind", lapply(cluster_features, as.data.frame)) 

但結果一切就緒成一列,像這樣:

head(x) 
         X[[i]] 
cluster1.dui   281673 
cluster1.control   10759 
cluster1.physic   10756 
cluster1.dui_physic  10756 
cluster1.physic_control 10756 
cluster1.alcohol   2917 

有沒有我的列表導出作爲一個CSV方式屏幕截圖中的格式?一列中的鍵,另一列中的值?

回答

1

如果我理解正確,你有一個命名向量的列表,&你想將每個向量轉換成名爲&值的2列數據幀。試試這個:

result <- lapply(seq_along(cluster_features), 
       function(i){data.frame(source = paste0("cluster", i), 
             key = names(cf[[i]]), 
             value = cf[[i]])}) %>% 
    data.table::rbindlist() 

> head(result) 
    source   key value 
1: cluster1   dui 281673 
2: cluster1  control 10759 
3: cluster1   physic 10756 
4: cluster1  dui_physic 10756 
5: cluster1 physic_control 10756 
6: cluster1  alcohol 2917 

如果您不需要區分源,你可以在數據幀跳過第一列。

+0

是的,非常感謝! –