【问题标题】:Ordering rows when they are not numeric当它们不是数字时对行进行排序
【发布时间】:2017-07-16 01:26:31
【问题描述】:

使用下面的df,我根据group/year的每个组合制作了每个单元的频率表。

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

有没有一种方法可以在更改表格以将单位放在行上之后,根据 2016 年 Total 组的 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列排序的

【问题讨论】:

  • 您已经列出了您期望它生成的输出,但是您能列出您的代码正在生成的输出吗?谢谢。

标签: r sorting dplyr tidyr


【解决方案1】:

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

在问题上运行代码后,我做了以下事情:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2019-05-07
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多