2017-07-16 16 views
-2

使用下面的df,我根據group/year的每個組合製作了每個單元的頻率表。當它們不是數字時排序行

獲得絕對和相對頻率後,我貼的值轉換爲一列Frequency

有沒有一種方法,我可以改變表後,對行的單位,讓他們降序排序基於Total組在2016年的n?我希望我的最終輸出沒有與nprop行,只有Frequency

df <- data.frame(cbind(sample(c('Controle','Tratado'), 
           10, replace = T), 
         sample(c(2012,2016), 10, T), 
         c('A','B','A','B','C','D','D','A','F','A'))) 

colnames(df) <- c('Group', 'Year', 'Unit') 

table <- df %>% 
    group_by(Year, Group) %>% 
    count(Unit) %>% 
    mutate(prop = prop.table(n)) %>% 
    bind_rows(df %>%            
       mutate(Group ="Total") %>%       
       group_by(Year, Group) %>%       
       count(Unit)) %>% 
    mutate(prop = prop.table(n)) 

is.num <- sapply(table, is.numeric) 
table[is.num] <- lapply(table[is.num], round, 4) 
table <- table %>% 
    mutate(Frequency = paste0(n,' (', 100*prop,'%)')) 

table <- table %>% 
    gather(type, measurement, -Year, -Group, -Unit) %>% 
    unite(year_group, Year:Group, sep = ":") %>% 
    spread(year_group, measurement) 

以下是我期待產生:

Unit  type 2012:Total 2012:Tratado 2016:Controle 2016:Total 2016:Tratado 
1 A Frequency 2 (66.67%) 2 (66.67%)    - 2 (28.57%)  2 (100%) 
2 D Frequency   -   -  2 (40%) 2 (28.57%)   - 
3 B Frequency 1 (33.33%) 1 (33.33%)  1 (20%) 1 (14.29%)   - 
4 C Frequency   -   -  1 (20%) 1 (14.29%)   - 
5 F Frequency   -   -  1 (20%) 1 (14.29%)   - 

公告根據2016:Total

列對結果進行排序

回答

0

剛剛發現了一種方法我自己,可能不是最好的。

上的問題運行代碼後,我也做了以下內容:

table <- subset.data.frame(table, type == 'Frequency') 

table <- table %>% 
    mutate(value = substr(Total_2016, 1, nchar(Total_2016) - 7)) %>% 
    mutate(value = as.numeric(value)) %>% 
    arrange(desc(value)) 
相關問題