[英]How stack multiple pivot tables based on multiple filters in EXCEL or R
我有一個我創建的 pivot 表。 該表按地區匯總數據,可以按 2 個類別(年齡、收入)過濾。 我如何創建一個表,以便每個類別組合(例如幼兒和低於 50% FPL,以及幼兒,所有收入)在每個聚合中表示。 到目前為止,我正在過濾年齡和收入的所有組合,只是復制並粘貼到新的電子表格中。 我鏈接了一個視頻,展示了我的意思
https://drive.google.com/file/d/1kUvDNxijXWZyJCCdVy398Gd0uq8vUFvY/view?usp=sharing
我願意在 Excel 或 R 中這樣做。
非常感謝你的幫助, Rouzbeh
為了在 Excel 中執行此操作,您需要第三方附加組件或至少在 VBA 中進行編碼才能執行此操作。
在 R 中您可以找到解決方案。 這里有一個類似的問題。 這還沒有被標記為已回答。
R 解決方案在 Base-R 中,您可以使用 aggregate() pivot。 在 reshape2、data.table 和 dyplr 等其他庫中還有其他 function。 如果您對這些庫感到滿意,請查找它們的聚合或按功能分組。
我不知道你是否有標志來確定一個主題是否可以閱讀。 在這種情況下,我將使用自定義聚合。 但如果不是這種情況,您可以使用任何傳統的聚合函數。
#Costume formula counting flags
counEle <- function(x){
a=length(which(x=="x"))}
然后:
#Create all posibles combinations using Age and Income
combination = expand.grid(unlist(data["Age"]),unlist(data["Income"]))
#Eliminate duplicated combinations
combination=unique(combination)
#Create the loop that filters and aggregate for each combination.
for(i in 1:nrow(combination)){
new_data=data[data$Age==combination[i,1] & data$Income==combination[i,2],]
#Check that the data frame has more than 0 columns so it could be aggregated
if(nrow(new_data)>0){
#Aggregate the data with the values in place
print(try(aggregate(Eligibility~Age+Income+County,new_data,counEle)))
}
}
總數位於“資格”列中,這是我們想要衡量的。 這應該是 output 所有可能的組合(請注意 try() 的錯誤處理程序。如果您想忽略計數為 0 的位置,您可以添加一個條件為 >0 的附加步驟。然后將每個結果寫在 csv 上或使用一個庫,將其寫在 excel 選項卡上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.