我正在使用 R 中的 for 循环为各个主题制作一些条形图。这些图表似乎是正确的,但问题是我需要使用它们的主题 ID (subID) 为图表添加标题,这就是它们所列出的内容在我循环的列表中。所以我有一个数据帧列表,列表中的每个元素都是不同的 subID,但我无法将 subID 放入图表的标题中。
这是我正在使用的简化示例:
SubID <- 1, 1, 2, 2, 3, 3
x <- c('scary', 'neutral', 'scary', 'neutral', 'scary', 'neutral')
y <- 98, 60, 60, 20, 80, 30
df <- data.frame(SubID, x, y)
print(df)
然后我像这样分割数据框:
df_list <- split(df, df$subid)
首先,我尝试使用paste0():
for (subid in df_list) {
plot <- ggplot(subid, aes(x, y)) +
geom_bar(position='dodge', stat='summary', fun='mean') + # make it show mean of y var
ggtitle(paste0("Ratings by face for ", subid)) # title of graph
print(plot)
}
但这只是使用了值列表(即 c(1,1) 的面部评级),这绝对不是我想要的(在我的实际数据中,它从数据帧中的不同列中提取数字列表,这更糟)。
然后我尝试使用名称():
for (subid in df_list) {
plot <- ggplot(subid, aes(x, y)) +
geom_bar(position='dodge', stat='summary', fun='mean') + # make it show mean of y var
ggtitle(paste0("Ratings by face for ", names(df_list))) # title of graph
print(plot)
}
但这仅使用列表中的第一项,因此所有图的标题都是“Ratings by face for 1”,而不是根据 subid 进行更改。
图本身只是在迭代中提取 subid 的数据,这是正确的;我就是无法让标题发挥作用。我还尝试了其他一些事情,例如在绘图函数之外设置标题,添加 as.character(subid),但我还没有得到任何工作,所以任何帮助将不胜感激!我对 R 也很陌生,尤其是在循环方面,所以据我所知,答案是显而易见的。
迭代
names(df_list)
,并使用每个名称索引到df_list
:
library(ggplot2)
for (subid in names(df_list)) {
plot <- ggplot(df_list[[subid]], aes(x, y)) +
geom_bar(position='dodge', stat='summary', fun='mean') +
ggtitle(paste0("Ratings by face for ", subid))
print(plot)
}
或使用
purrr::iwalk()
:
iwalk(df_list, \(df, nm) {
plot <- ggplot(df, aes(x, y)) +
geom_bar(position='dodge', stat='summary', fun='mean') +
ggtitle(paste0("Ratings by face for ", nm))
print(plot)
})