查看数据帧的内容时是否可以截断输出? [英] Is it possible to truncate output when viewing the contents of dataframes?
本文介绍了查看数据帧的内容时是否可以截断输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有一些很长的注释列的数据框。当我显示它们时,它们分为不同的块,这使得跨行读取变得困难。是否可以更改R中的设置或修改对data.frame的调用以截断特定长度的字符串?
I have a data frame with some very long "comments" columns. When I have them displayed they are broken into different blocks, making it hard to read across rows. Is it possible to change a setting in R or modify the call to data.frame to truncate strings at a certain length?
例如:3列数据框
Example: a 3-column dataframe
data.frame(cbind(rep(1,5),rep(c("very very long obnoxious character string here" ,"dog","cat","dog",5)),rep(c("very very long obnoxious character string here" ,"dog","cat","dog",5))))
在我的屏幕上看到的结果数据帧:
Resulting dataframe as seen on my screen:
X1 X2
1 1 very very long obnoxious character string here
2 1 dog
3 1 cat
4 1 dog
5 1 5
X3
1 very very long obnoxious character string here
2 dog
3 cat
4 dog
5 5
推荐答案
我推荐一种类似这样的显式方式:
I recommend a kind of the explicit way like this:
f <- function(x) data.frame(lapply(x, substr, 1, 5))
用法:
> f(d)
X1 X2 X3
1 1 very very
2 1 dog dog
3 1 cat cat
4 1 dog dog
5 1 5 5
尽管可以更改默认行为,但我不建议:
Although it is possible to change the default behavior, I don't recommend:
body(format.data.frame)[[5]] <- quote(for (i in 1L:nc) rval[[i]] <- substr(format(x[[i]], ..., justify = justify), 1, 5))
unlockBinding("format.data.frame", baseenv())
assign("format.data.frame", format.data.frame, pos = baseenv())
lockBinding("format.data.frame", baseenv())
rm(format.data.frame)
使用情况:
> d
X1 X2 X3
1 1 very very
2 1 dog dog
3 1 cat cat
4 1 dog dog
5 1 5 5
这篇关于查看数据帧的内容时是否可以截断输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文