在 R 中,我有一個輸入資料集(“my_data”)。使用這個資料集,我制作了一些圖并像這樣保存它們:
library(htmltools)
library(plotly)
fig1 = plot_ly(my_data, x =~ var1, y = ~var2, type = 'bar', name = 'Plot 1')
fig2 = plot_ly(my_data, x =~ var1, y = ~var3, type = 'bar', name = 'Plot 2')
fig3 = plot_ly(my_data, x =~ var1, y = ~var4, type = 'bar', name = 'Plot 3')
fig4 = plot_ly(my_data, x =~ var1, y = ~var5, type = 'bar', name = 'Plot 4')
# final result
doc <- htmltools::tagList(
div(fig1, style = "float:left;width:50%;"),
div(fig2,style = "float:left;width:50%;"),
div(fig3, style = "float:left;width:50%;"),
div(fig4, style = "float:left;width:50%;")
)
# save the final result
htmltools::save_html(html = doc, file = "final.html")
假設現在我有一個名為“my_data_2”的新資料集,其格式與“my_data”完全相同。是否有可能將上述代碼轉換為一個函式,以便在“my_data_2”上執行完全相同的程序?
例如:
some_function <- function (my_data) {
library(htmltools)
library(plotly)
fig1 = plot_ly(my_data, x =~ var1, y = ~var2, type = 'bar', name = 'Plot 1')
fig2 = plot_ly(my_data, x =~ var1, y = ~var3, type = 'bar', name = 'Plot 2')
fig3 = plot_ly(my_data, x =~ var1, y = ~var4, type = 'bar', name = 'Plot 3')
fig4 = plot_ly(my_data, x =~ var1, y = ~var5, type = 'bar', name = 'Plot 4')
# final result
doc <- htmltools::tagList(
div(fig1, style = "float:left;width:50%;"),
div(fig2,style = "float:left;width:50%;"),
div(fig3, style = "float:left;width:50%;"),
div(fig4, style = "float:left;width:50%;")
)
# save the final result
htmltools::save_html(html = doc, file = "final.html")
}
然后,在呼叫此函式時:
some_function(my_data_2)
最終會為這個新檔案產生相同的結果嗎?
謝謝!
uj5u.com熱心網友回復:
假設列具有相同的名稱,這將起作用。
some_function <- function(df1) {
plots <- map(1:4,
function(k) { # create the graphs
plot_ly(df1, x = ~var1, y = df1[, paste0("var", k 1)],
type = "bar", name = paste0("Plot", k))
})
sty <- "float:left;width:50%;" # create the style
doc <- tagList(map(1:4, # combine style & graphs
function(j) {
div(plots[j], style = sty)
}))
save_html(html = doc, file = "final.html")
}
如果您想在創建圖表之前預覽它,您可以這樣做。
library(plotly)
library(htmltools)
library(tidyverse) # for map in purrr
some_function <- function(df1) {
plots <- map(1:4,
function(k) { # create the graphs
plot_ly(df1, x = ~var1, y = df1[, paste0("var", k 1)],
type = "bar", name = paste0("Plot", k))
})
sty <- "float:left;width:50%;" # create the style
doc <- tagList(map(1:4, # combine style & graphs
function(j) {
div(plots[j], style = sty)
}))
# save_html(html = doc, file = "final.html")
doc
}
# arbitrary data to demonstrate with
df1 <- data.frame(var1 = rep(c("this", "that"), 5),
var2 = 1:10,
var3 = 10:1,
var4 = 15:6,
var5 = 6:15)
html_print(some_function(df1)) # show in viewer pane
這是從最后一次呼叫中產生的。

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529074.html
標籤:r功能
下一篇:將值從一行保留到下一行
