How to use R's sprintf to create fixed width strings with fill whitespace at the END?

前端 未结 3 627
说谎
说谎 2020-12-31 01:27

I have vector of strings and want to create a fixed with string out of that. Shorter strings should be filled up with white spaces. E.g.:

c(\"fjdlksa01dada\"         


        
相关标签:
3条回答
  • 2020-12-31 01:36

    That is almost more of a standard "C" rather than R question as it pertains to printf format strings. You can even test this on a command-prompt:

    edd@max:~$ printf "[% 8s]\n" foo
    [     foo]
    edd@max:~$ printf "[%-8s]\n" foo
    [foo     ]
    edd@max:~$ 
    

    and in R it works the same for padding left:

    R> vec <- c("fjdlksa01dada","rau","sjklf")
    R> sprintf("% 8s", vec)
    [1] "fjdlksa01dada" "     rau"      "   sjklf"     
    R> 
    

    and right

    R> sprintf("%-8s", vec)
    [1] "fjdlksa01dada" "rau     "      "sjklf   "     
    R> 
    

    Edit: Updated once I understood better what @ran2 actually asked for.

    0 讨论(0)
  • 2020-12-31 01:46

    The stringr package provides str_pad:

    library(stringr)
    x <- c("fjdlksa01dada","rau","sjklf")
    str_pad(x, width=8, side="right")
    

    which yields:

    [1] "fjdlksa01dada" "rau     "      "sjklf   "
    
    0 讨论(0)
  • 2020-12-31 01:55

    Add a minus in front of the 8 to get a left-aligned padded string

    0 讨论(0)
提交回复
热议问题