我有一個函式可以做幾件事,包括生成 ggplot 物件。然后我將此函式傳遞給 purrr::map() 以迭代嵌套資料。我需要為函式中的每個物件添加一個idas ,但是這些物件是由另一個 R 包中的另一個函式創建的,因此我必須在我的函式中創建物件之后添加。當我嘗試使用迭代時,出現錯誤。ggtitleggplotggplotggtitleggplotpurrr::map()
我認為這個執行緒可能會有所幫助,但我無法弄清楚如何為我的示例撰寫代碼:將標題添加到使用 map() 創建的 ggplots
這是一個非常簡化的函式,我認為它復制了我的問題:
library("tidyverse")
dat <-
structure(list(id = c("07060710", "07060710", "07060710", "07060710",
"07060710", "07060710", "07060710", "07060710", "07060710", "07060710",
"07263295", "07263295", "07263295", "07263295", "07263295", "07263295",
"07263295", "07263295", "07263295", "07263295"), y = c(-0.1,
0.1, 0, 0, -0.1, -0.1, -0.1, 0, -0.1, -0.2, 0.4, 0.5, 0.5, 0.5,
0.9, 0.7, 0.9, 0.9, 0.4, 0.4), x = c(1, 1.8, 1.3, 1.3, 0.7, 0.3,
1.5, 0.9, 1, 0.5, 1.1, 1, -0.1, -0.4, 3.2, 2.4, 3, 3.3, 0.7,
1)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-20L))
runLM = function(df) {
# Here I try to extract the id
# And I think this is what causes the error
id_title <- unique(df$id)
lm_fit <- lm(y ~ x, data = df)
# This is a simplified plot function for this example
# The actual initial plot is created by a function from another package
# So I cannot manipulate the initial ggplot function
# I can only manipulate the ggplot object after it is created
plot_init <-
df %>%
ggplot(aes(x = x, y = y))
geom_point()
# Here I try to add the 'id' as a the plot title
plot_fin <- plot_init
ggtitle(id_title)
return(plot_fin)
}
然后我將此函式傳遞給:
fit_lm <-
dat %>%
group_by(id) %>%
nest() %>%
mutate(model = map(data, ~runLM(df = .x)))
# Here should be the plot, but I get an error when I try to iterate using map()
fit_lm[[3]][[1]]
uj5u.com熱心網友回復:
嵌套后id,存盤在串列列中的資料框中沒有列data。而是id_title向您的函式添加一個引數,并用于map2回圈遍歷嵌套資料的id和data列:
library("tidyverse")
runLM = function(df, id_title) {
lm_fit <- lm(y ~ x, data = df)
plot_init <-
df %>%
ggplot(aes(x = x, y = y))
geom_point()
plot_fin <- plot_init
ggtitle(id_title)
return(plot_fin)
}
fit_lm <- dat %>%
group_by(id) %>%
nest() %>%
mutate(model = map2(data, id, ~runLM(df = .x, id_title = .y)))
fit_lm$model
#> [[1]]

#>
#> [[2]]

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383092.html
上一篇:R中的布朗運動/回圈
