我有一個帶有代碼的列出的資料框:
df1 <- data.frame(ID = rep(c("P-1000", "P-10001", "P-10002", "P-1003", "P-1004"),3),
Visit = c(rep("M1",5), rep("M4",5), rep("M17",5)),
Value = runif(15))
df2 <- data.frame(ID = rep(c("P-1000", "P-10001", "P-10002", "P-1003", "P-1004"),3),
Visit = c(rep("M1",5), rep("M4",5), rep("M17",5)),
Value = runif(15))
df3 <- data.frame(ID = rep(c("P-1000", "P-10001", "P-10002", "P-1003", "P-1004"),3),
Visit = c(rep("M1",5), rep("M4",5), rep("M17",5)),
Value = runif(15))
sampledata<- list(df1, df2, df3)
names(sampledata)<- c("A", "C", "Z")
我正在嘗試為其繪制情節。我正在嘗試為每個資料幀的每個 ID 繪制圖(例如,1 個圖將用于資料幀 A 中的 P-1000)。最后,我想通過資料框將這些圖保存在單獨的 pdf 中(例如,與資料框 A 相關的所有圖的 1 個 pdf,另一個用于資料框 B 等)。我不太確定該怎么做。我目前的代碼試用如下:
sample_data_plots <- lapply(seq_along(sampledata),function(i) {
sampledata[[i]] %>% filter(!is.na(Visit)) %>% group_by(ID) %>%
mutate(Visit = factor(Visit, levels = c("M1", "M4", "M17"))) %>%
ggplot(aes(x = Visit, y = Value)) geom_boxplot()
labs(title = paste("Values of", names(sampledata)[i], "for", "ID",
#this is the variable ID
),
y = "Value",
x = "Visit")})
我在運行中沒有問題:
lapply(seq_along(sampledata), function(i) {
sampledata[[i]] %>% filter(!is.na(Visit)) %>%
mutate(Visit = factor(Visit, levels = c "M1", "M4", "M17"))) %>%
ggplot(aes(x = Visit, y = Value)) geom_boxplot()
labs(title = paste("Value", names(sampledata)[i]),
y = "Value",
x = "Visit") })
但這給出了所有 ID 的每個資料幀的圖表
任何幫助將不勝感激。謝謝!
uj5u.com熱心網友回復:
考慮purrr::map2跨資料框串列及其名稱dplyr::group_map應用函式,并按 ID 組應用函式。
build_plot <- function(sub_df) {
sub_df %>%
filter(!is.na(Visit)) %>%
mutate(Visit = factor(Visit, levels=c("M1", "M4", "M17"))) %>%
ggplot(aes(x=Visit, y=Value))
geom_boxplot()
labs(title = paste("Value", sub_df$ID[1]), y="Value", x="Visit")
}
run_groups <- function(main_df, df_name) {
# BUILD PLOTS BY ID
plot_list <- main_df %>%
group_by(ID) %>%
group_map(build_plot)
# SAVE PLOTS TO SINGLE PDF
ggplot2::ggsave(
filename = paste0(df_name, "_plots.pdf"),
plot = gridExtra::marrangeGrob(plot_list, nrow=1, ncol=1),
width = 15, height = 9
)
return(plot_list)
}
# CREATE PDFS BY DATA FRAME
myplots <- purr::map2(sample_data, names(sample_data), run_groups)
類似的baseR 方法分別是lapply: Map(wrapper to mapply) 和by(wrapper to tapply) 的兄弟。
run_groups <- function(main_df, df_name) {
# BUILD PLOTS BY ID
plot_list <- by(main_df, main_df$ID, build_plot)
...
}
# CREATE PDFS BY DATA FRAME
myplots <- Map(run_groups, sample_data, names(sample_data))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/469455.html
上一篇:如何清理包含混合變數的列,例如char格式的curreny、空格、R中的字串
下一篇:JavaSwing鍵盤格式不正確
