【问题标题】:Print or Retain output from each run of a loop in R markdown notebook在 R markdown notebook 中打印或保留每次循环运行的输出
【发布时间】:2019-12-26 17:12:50
【问题描述】:

我正在尝试通过循环遍历列表并在每个数据帧上运行 head() 和 tail() 来报告数据帧列表中每个数据帧的数据内容。但是,RStudio 中到笔记本的输出总是只是最后一个。

例子:

# Initialize Variables
list_of_df <- list()
dummy_v1 <- c(1:3)
dummy_v2 <- c(4:6)
dummy_v3 <- 1

for (i in 1:3) {
  dummy_v3 <- c(i:i+3)
  dummy_v3
  dummy_df <- data.frame(dummy_v1, dummy_v2, dummy_v3)
  list_of_df[[i]] <- dummy_df
}


# Illustrate my Problem

# I would like to print the following output into the notebook report in a for loop for each dataframe in list_of_df:
head(list_of_df[[1]])
tail(list_of_df[[1]])

for (i in 1:length(list_of_df)) {
  head(list_of_df[[i]])
  tail(list_of_df[[i]])
}

# output only shows the last iteration's head and tails.

实际上,我有 130 个数据框,每个数据框都有大约 700 个对 116 或 117 个变量的时间序列观察,因此我需要以编程方式执行此操作。我想得到这个输出,这样我就可以对数据帧进行快速的完整性检查,然后继续进行时间序列分析。 TIA 为您提供帮助!


回答!!!

lapply 对我们 R 新手来说是一个有趣的功能;语法没有显式地将参数传递给应用的函数。对我有用的解决方案在语法上很优雅:

Report <- function(x) {
  list(sprintf("Details of %s", names(x)),
    sprintf("Columns: %d", ncol(x)),
    sprintf("Rows: %d", nrow(x)),
    head(x),
    tail(x))
}

lapply(list_of_df, Report)

输出不是那么优雅,但它是可行的,让我可以快速阅读结果。

【问题讨论】:

    标签: r dataframe output report


    【解决方案1】:

    如果我们想要单独的输出,使用list 作为base R 中的返回而不加载任何外部包

    lapply(list_of_df, function(x) list(head(x), tail(x)))
    

    使用for循环,需要存储在一个对象中

    out <- vector('list', length(list_of_df))
    for(i in seq_along(list_of_df)) {
        out[[i]][["head"]] <- head(list_of_df[[i]])
        out[[i]][["tail"]] <-  tail(list_of_df[[i]])
    }
    

    或者单行

    for(i in seq_along(list_of_df)) {
       out[[i]][c("head", "tail")] <- list(head(list_of_df[[i]]), tail(list_of_df[[i]]) )
        }
    

    【讨论】:

    • 谢谢。 lapply 的语法对我来说有点奇怪,但这很有效。我已经编辑了我的问题以包含工作正确的代码。
    【解决方案2】:

    我强烈建议您不要使用基于循环的方法来解决时间序列问题,请查看 https://github.com/tidyverts 包和 https://www.tidyverse.org/

    不管怎样,你可以用一个简单的方法解决这个问题

    library(tidyverse)
    map(.x = list(head,tail),.f = exec,list_of_df)
    

    【讨论】:

    • 对于我的新手,您能解释一下 map 函数的参数吗?
    • 当然 map 接受一个向量并且 a 应用一个函数,exec 执行一个函数,所以如果你将一个函数列表传递给 map 并且函数是 exec,我们执行一个函数列表,然后你只需要传递这些函数将被执行的内容,在本例中为 list_of_df。
    • 这也可以,但不能作为参数扩展到列表 map(list_of_df, ~ list(head = head(.), tail = tail(.)))
    • 我读了几本书来解惑。所以map的语法是:map(作用的向量,作用的函数)。在这种情况下, .x = list(head, tail) 将向量定义为我想要执行的函数的列表。 .f = exec 告诉 map 它将运行列表上的 exec 函数,这转换为执行列表上的函数。可能只是我的新手,但我发现 R 的语法有点复杂。不过谢谢!
    • 这确实需要一些时间来习惯阅读我的嘶嘶声示例来帮助你? twosidesdata.netlify.com/2019/12/22/fizzbuzz-in-the-tidyverse
    猜你喜欢
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    相关资源
    最近更新 更多