#r #for-loop #dplyr #gt
Вопрос:
Дана следующая выборка данных:
df lt;- structure(list(category = c("food", "food", "food", "food", "electronic product", "electronic product", "electronic product", "electronic product" ), type = c("vegetable", "vegetable", "fruit", "fruit", "computer", "computer", "other", "other"), variable = c("cabbage", "radish", "apple", "pear", "monitor", "mouse", "camera", "calculator"), price = c(6, 5, 3, 2.9, 2000, 10, 600, 35), quantity = c(2L, 4L, 5L, 10L, 1L, 3L, NA, 1L)), class = "data.frame", row.names = c(NA, -8L))
Я могу нарисовать график таблицы с помощью кода ниже:
library(gt) library(magrittr) dt lt;- df %gt;% group_by(category) %gt;% gt() %gt;% tab_header( title = md("Category name") )%gt;% tab_style( locations = cells_column_labels(columns = everything()), style = list( #Give a thick border below cell_borders(sides = "bottom", weight = px(3)), #Make text bold cell_text(weight = "bold") ) ) %gt;% tab_style( locations = cells_row_groups(groups = everything()), style = list( cell_text(weight = "bold") ) ) %gt;% cols_align(align = "center", columns = everything()) dt gt::gtsave(dt, file = file.path("./Category_name.png"))
Из:
Теперь я надеюсь зациклиться category
и group_by(type)
сгенерировать несколько графиков для каждого category
. В то же время мне также нужно переименовать каждый участок с именем category
путем изменения gtsave(dt, file = file.path("./Category_name.png"))
и tab_header(title = md("Category name"))%gt;%
динамического изменения.
How could I acheive that with R and gt
package? Thanks.
EDIT: to plot for food category
food lt;- df %gt;% filter(category=='food') %gt;% group_by(type) %gt;% gt() %gt;% tab_header( title = md("Food") )%gt;% fmt_missing( columns = where(is.numeric), missing_text = "-" ) %gt;% tab_style( locations = cells_column_labels(columns = everything()), style = list( #Give a thick border below cell_borders(sides = "bottom", weight = px(3)), #Make text bold cell_text(weight = "bold") ) ) %gt;% tab_style( locations = cells_row_groups(groups = everything()), style = list( cell_text(weight = "bold") ) ) %gt;% cols_align(align = "center", columns = where(is.character)) %gt;% cols_align(align = "right", columns = where(is.numeric)) gt::gtsave(food, file = file.path("./food.png"))
Ответ №1:
Я бы превратил ваш код в функцию, затем поместил каждую категорию в свой собственный фрейм данных в списке, а затем применил функцию с purrr::map
помощью .
library(tidyverse) library(gt) plot_category lt;- function(x) { p lt;- x %gt;% dplyr::select(-category) %gt;% dplyr::group_by(type) %gt;% gt() %gt;% tab_header(title = md(str_to_title(x$category[1]))) %gt;% fmt_missing(columns = where(is.numeric), missing_text = "-") %gt;% tab_style( locations = cells_column_labels(columns = everything()), style = list( #Give a thick border below cell_borders(sides = "bottom", weight = px(3)), #Make text bold cell_text(weight = "bold") ) ) %gt;% tab_style(locations = cells_row_groups(groups = everything()), style = list(cell_text(weight = "bold"))) %gt;% cols_align(align = "center", columns = where(is.character)) %gt;% cols_align(align = "right", columns = where(is.numeric)) gt::gtsave(p, file = file.path(paste0("./", x$category[1], ".png"))) } df %gt;% dplyr::group_split(category) %gt;% purrr::map(plot_category)
Выход
Комментарии:
1. Большое спасибо, вы сэкономили мне время. Как я мог удалить
category
столбец в выводе, поскольку он уже указан в названии каждого участка? это означает , что я надеюсь сохранить 3 столбцаvariable
price
иquantity
в окончательном выводе.2. @ahbon Нет проблем. Вы можете просто добавить строку в функцию для удаления
category
с помощьюdplyr::select(-category)
. Я обновил ответ, чтобы отразить это.