如何在r

时间:2019-05-14 17:29:32

标签: r

我正在寻找有关如何在中显示数据表的示例或想法。汇总了多个级别的Rmd文档。因此,在下面的示例中,日期,名称,数量,费率和值在项目级别具有总计。

下面我只是制作了一个例子来说明我的意思:

names <- c('note','pen','book','note','pen','book')
qty <- c(150, 100, 200, 50, 150, 75)
date <- c('1-mar-2019','1-mar-2019','1-mar-2019', '2-mar-2019','2-mar-2019','2-mar-2019')
rate <- c(10, 5, 20, 10, 5, 20)

stationary <- data.frame(date, names, qty, rate)

stationary$value = stationary$qty*stationary$rate

我希望在下面获得这样的结果

enter image description here

1 个答案:

答案 0 :(得分:0)

编辑:格式化的更新代码

使用dplyr

library(tidyverse)

stationary <- stationary %>% 
    mutate(value = rate*qty)

stationary1 <- stationary %>%
    group_by(names) %>% 
    summarise(qty = sum(qty), value = sum(value)) %>% 
    ungroup() %>% 
    mutate(names = paste0(names, " total")) %>% 
    bind_rows(stationary)

stationary1 %>%
    filter(grepl("total", names)) %>%
    summarise(qty = sum(qty),
              value = sum(value)) %>% 
    mutate(names = "Total (Grand)") %>% 
    bind_rows(stationary1) %>% 
    arrange(names) %>% 
    select(date, names, qty, rate, value) %>% 
    mutate_all(as.character) %>%
    replace_na(list(date = "", names = "", qty = "", rate = "", value = ""))

结果如下:

# A tibble: 10 x 5
   date       names         qty   rate  value
   <chr>      <chr>         <chr> <chr> <chr>
 1 1-mar-2019 book          200   20    4000 
 2 2-mar-2019 book          75    20    1500 
 3 ""         book total    275   ""    5500 
 4 1-mar-2019 note          150   10    1500 
 5 2-mar-2019 note          50    10    500  
 6 ""         note total    200   ""    2000 
 7 1-mar-2019 pen           100   5     500  
 8 2-mar-2019 pen           150   5     750  
 9 ""         pen total     250   ""    1250 
10 ""         Total (Grand) 725   ""    8750