【发布时间】:2014-06-23 19:03:54
【问题描述】:
如何让 R 检查对象是否太大而无法在控制台中打印?这里的“太大”是指大于用户定义的值。
示例:您有一个列表 f_data,其中包含两个元素 f_data$data(一个 100MB 的数据帧)和 f_data$info(例如,一个向量)。假设您要检查f_data$data data.frame 的前几个条目,但您犯了一个错误并键入head(f_data) 而不是head(f_data$data)。 R 将尝试将f_data 的全部内容打印到控制台(这将花费很长时间)。
是否可以设置一个选项来抑制大于 1MB 的对象的输出?
编辑:谢谢你们的帮助。在实现max.rows 选项后,我意识到这确实提供了所需的输出。但是输出需要很长时间才能显示的问题仍然存在。下面我给你举个恰当的例子。
df_nrow=100000
df_ncol=100
#create list with first element being a large data.frame
#second element is a short vector
test_list=list(df=data.frame(matrix(rnorm(df_nrow*df_ncol),nrow=df_nrow,ncol=df_ncol)),
vec=1:110)
#only print the first 100 elements of an object
options(max.print=100)
#head correctly displays the first row of the data.frame
#BUT for some reason the output takes really long to show up in the console (~30sec)
head(test_list)
#let's try to see how long exactly
system.time(head(test_list))
# user system elapsed
# 0 0 0
#well, obviously system.time is not the proper tool to measure this
#the same problem if I just print the object to the console without using head
test_list$df
我假设 R 对正在打印的对象执行某种分析,这需要很长时间。
编辑 2:
根据我下面的评论,我检查了如果我使用 matrix 而不是 data.frame,问题是否仍然存在。
#create list with first element being a large MATRIX
test_list=list(mat=matrix(rnorm(df_nrow*df_ncol),nrow=df_nrow,ncol=df_ncol),vec=1:110)
#no problem
head(test_list)
#no problem
test_list$mat
难道是data.frame 对象的控制台输出没有真正有效地实现?
【问题讨论】:
-
我一般设置
options(max.print)来防止控制台溢出。不过,这会限制打印字符的数量,而不是大小。 -
@RomanLuštrik 我相信它实际上限制了“元素”的打印,这大约是 data.frame 的行和列表的条目。
-
啊,对不起。这就是我的意思,元素。感谢您的更正。我刚刚检查过,一个元素将是 data.frame 中的一个数字。我有一个包含 40 个变量的 data.frame,并将打印限制为 500。它只显示 12 行(12 * 40 = 480)。
-
谢谢你们。请看我上面的编辑。
-
我现在看到,如果我将
data.frame替换为matrix,则不会出现此问题。也许这与data.frames 的存储方式有关。据我所知,它们是一个向量列表,每个向量都是data.frame的一列。由于max.print适用于行,R不能简单地遍历data.frame的元素...