使用长字符串变量打印数据框

时间:2018-09-22 22:03:45

标签: r dataframe rstudio

我有一个数据框,其中包含对调查问题的描述,可能很长。我正在尝试找出一种整齐地打印它们的方法。这是一个示例:

foo <- data.frame(v1 = 1:5, 
                  v2 = rep(c("This is a really long description of a survey question that gives a bunch of information about the question and can be very long blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah"), 5), 
                  v3 = 6:10)

我希望打印输出看起来像这样:

  v1   v2                                       v3
1  1   This is a really long description of     6
       a survey question that gives a bunch 
       of information about the question and
       can be very long blah blah blah blah 
       blah blah blah blah blah blah blah 
       blah blah blah blah blah blah blah
2  2   This is a really long description of     7
       a survey question that gives a bunch 
       of information about the question and
       can be very long blah blah blah blah 
       blah blah blah blah blah blah blah 
       blah blah blah blah blah blah blah
3  3   This is a really long description of     8
       a survey question that gives a bunch 
       of information about the question and
       can be very long blah blah blah blah 
       blah blah blah blah blah blah blah 
       blah blah blah blah blah blah blah
4  4   This is a really long description of     9
       a survey question that gives a bunch 
       of information about the question and
       can be very long blah blah blah blah 
       blah blah blah blah blah blah blah 
       blah blah blah blah blah blah blah
5  5   This is a really long description of     10
       a survey question that gives a bunch 
       of information about the question and
       can be very long blah blah blah blah 
       blah blah blah blah blah blah blah 
       blah blah blah blah blah blah blah

2 个答案:

答案 0 :(得分:1)

您可以使用abbreviate()DT::datatable()。这样,您可以自动缩短文本并在单击时查看全文:

library(DT)
texts <- paste0(1:5, "is is a really long description of a survey question that gives a bunch of information about the question and can be very long blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah")

foo <- data.frame(v1 = 1:5, 
                  v2 = paste0('<a href="#" onclick="alert(\'', texts, '\');">', 
                              abbreviate(texts, named = FALSE), '</a>'), 
                  v3 = 6:10)
datatable(foo, escape = FALSE)

enter image description here

答案 1 :(得分:1)

flextable::flextable(foo, cwidth = c(0.5,7,0.5))

enter image description here