【问题标题】:Using name of dataframe as graph title in a function in R when dataframes are being called from a list当从列表中调用数据框时,在 R 中的函数中使用数据框的名称作为图形标题
【发布时间】:2019-11-14 15:30:43
【问题描述】:

我想对初始数据帧的大量子集进行分析,每个子集数据帧都根据它们所代表的子集命名。

我已经制作了一个数据帧列表(以下称为 dflist),并在 for 循环中使用标识符“dataframe_in_list”在它们上运行一个函数。我尝试使用“deparse(substitute(dataframe_of_interest)) 作为标题,但它没有去掉原来的标题,即 mtcars_a 或 mtcars_b。

mtcars_a <- mtcars[1:16,]
mtcars_b <- mtcars[16:32,] 
plot_items <- function(dataframe_of_interest, item_x, item_y){
  plot(dataframe_of_interest[, item_x], dataframe_of_interest[, item_y],
                   main = deparse(substitute(dataframe_of_interest)))
}

dflist <- list(mtcars_a, mtcars_b)
for (dataframe_in_list in dflist){
  plot_items(dataframe_in_list, "mpg", "disp")
}

但是,每个图表的标题都是来自 for 循环的标识符,而不是它最初来自的真实数据框。

非常感谢任何建议!

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    我只会使用命名列表并遍历名称:

    mtcars_a <- mtcars[1:16,]
    mtcars_b <- mtcars[16:32,] 
    plot_items <- function(dataframe_of_interest, item_x, item_y, name){
      plot(dataframe_of_interest[, item_x], dataframe_of_interest[, item_y],
           main = name)
    }
    
    dflist <- list(mtcars_a = mtcars_a, mtcars_b = mtcars_b)
    for (name in names(dflist)){
      plot_items(dflist[[name]], "mpg", "disp", name)
    }
    

    将这些对象放入列表后,您将无法检索原始变量名称。毕竟,mtcars_a 只是指向内存中对象的指针,而列表只创建数据的副本并使用自己的指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多