【发布时间】: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)
输出不是那么优雅,但它是可行的,让我可以快速阅读结果。
【问题讨论】: