当行不是数字时对行进行排序

Ordering rows when they are not numeric

使用下面的 df,我根据 group/year.

的每个组合为每个单元制作了一个带有频率的 table

获得绝对频率和相对频率后,我将值粘贴到一列中Frequency

有没有一种方法可以在更改 table 以在行上显示单位后,让它们根据 Total 组中的 n 降序排列2016?我希望我的最终输出没有包含 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

列排序的

我自己找到了一个方法,可能不是最好的方法。

在问题的代码运行之后,我做了以下工作:

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))