遍历数据框列表并为每个图命名标题

Loop through a list of dataframes and name the title for each plot

我正在引用这个 example code 来生成一个包含多个子图的图,这些子图有自己的标题,但无法通过循环正确标记子图的标题。 为了便于说明,我以 1 by 2 plots 环境为例。

par(mfrow(1, 2))
require(fmsb)

data1=as.data.frame(matrix( sample(2:20, 10, replace=T) , ncol=10))
data2=as.data.frame(matrix( sample(2:20, 10, replace=T) , ncol=10))
colnames(data1)=c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" )
colnames(data2)=c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" )

df1=rbind(rep(20,10) , rep(0,10) , data1)
df2=rbind(rep(20,10) , rep(0,10) , data2)

my.list <- list(df1, df2)

for (i in my.list[[i]]) {

radarchart(i, axistype=1 , 

    #custom polygon
    pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4 , 

    #custom the grid
    cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,20,5), cglwd=0.8,

    #custom labels
    vlcex=0.8 
    )
}

但是,此代码块没有 return 任何内容,因为它要求输入是数据帧。另外,如果我想通过为每个数据框分配一个唯一的名称(比如,学生 1、学生 2)并将它们用作每个子图的标题,在 radarchart() 中放置一个 title 参数,我该如何实现在循环中?

您的代码有一些错误,这是预期的输出:

par(mfrow=c(1, 2)) #debugged

library(fmsb)

data1=as.data.frame(matrix( sample(2:20, 10, replace=T) , ncol=10))
data2=as.data.frame(matrix( sample(2:20, 10, replace=T) , ncol=10))
colnames(data1)=c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" )
colnames(data2)=c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" )

df1=rbind(rep(20,10) , rep(0,10) , data1)
df2=rbind(rep(20,10) , rep(0,10) , data2)

my.list <- list("df1" = df1, "df2" = df2) #name the list's elements

for (i in 1:length(my.list)) { #use i as list indexer, not to call the elements

  radarchart(my.list[[i]], axistype=1 , #call the list's elements

             #custom polygon
             pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4 , 

             #custom the grid
             cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,20,5), cglwd=0.8,

             #custom labels
             vlcex=0.8, 

             #title; calling the list's names
             title = names(my.list)[i] 
  )
}