在查看数据帧的内容时是否可以截断输出?

时间:2011-12-05 01:12:17

标签: r printing dataframe output-formatting

我有一个带有一些非常长的“评论”列的数据框。当我显示它们时,它们被分成不同的块,使得难以跨行读取。是否可以更改R中的设置或修改对data.frame的调用以截断一定长度的字符串?

示例:3列数据框

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))))

屏幕上显示的结果数据框:

  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

1 个答案:

答案 0 :(得分:12)

我推荐一种明确的方式:

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

虽然可以更改默认行为,但我不建议:

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