Printing dataframes with long strings in R

前端 未结 3 1839
挽巷
挽巷 2021-02-20 00:13

Let\'s have a dataframe with long strings in one column:

 df<-data.frame(short=rnorm(10,0,1),long=replicate(10,paste(rep(sample(letters),runif(1,5,8)),collaps         


        
相关标签:
3条回答
  • 2021-02-20 00:15

    This is one way:

    within(df, {
        long = paste(substr(long, 1, 10), "...", sep = "")
    })
    

    I use substr to get the first part of the string, than I use paste for the "...". To permanently change the characters in df, simply do:

    df = within(df, {
        long = paste(substr(long, 1, 10), "...", sep = "")
    })
    
    0 讨论(0)
  • 2021-02-20 00:22

    You can redefine the print.data.frame method, and in this function use substr to trim your character vectors to the desired maximum length:

    print.data.frame <- function (x, ..., maxchar=20, digits = NULL, quote = FALSE,
        right = TRUE, row.names = TRUE) 
    {
      x <- as.data.frame(
          lapply(x, function(xx)
                if(is.character(xx)) substr(xx, 1, maxchar) else xx)
      )
      base::print.data.frame(x, ..., digits=digits, quote=quote, right=right, 
          row.names=row.names)
    }
    

    Create data. Note my addition of stringsAsFactors=FALSE:

    df <- data.frame(
        short=rnorm(10,0,1),
        long=replicate(10,paste(rep(sample(letters),runif(1,5,8)),collapse="")),
        stringsAsFactors=FALSE
    )
    

    Print data.frame:

    print(df, maxchar=10)
            short       long
    1  -0.6188273 cpfhnjmeiw
    2  -0.0570548 bwcmpinedr
    3  -0.5795637 dcevnyihlj
    4   0.1977156 qzxlhvnarm
    5  -1.9551196 aiflwtkjdq
    6  -1.2429173 vlscerwhgq
    7  -0.5897045 fziogkpsyr
    8   0.4946985 pdeswloxcn
    9   0.3262543 kxlofchszd
    10 -1.8059621 wncaedpzty
    
    0 讨论(0)
  • 2021-02-20 00:34

    Uses dplyr and prints out a modified version of the original data frame (without changing it). Only shortens values which exceed specified length:

    library(dplyr)
    
    print.data.frame(df %>% mutate(long = ifelse(
        nchar(long > 11),
        paste0(substr(long, 1, 8), "..."),
        long
    )))
    
    0 讨论(0)
提交回复
热议问题