5

我有一个带有一些很长的“评论”列的数据框。当我让它们显示时,它们被分成不同的块,很难跨行阅读。是否可以更改 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
4

1 回答 1

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
于 2011-12-05T01:45:20.837 回答