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

吃可爱长大的小学妹 提交于 2019-12-18 12:49:33

问题


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","rau","sjklf")
sprintf("%8s")
# returns
[1] "fjdlksa01dada" "     rau"      "   sjklf"

But how can I get the additional whitespace at the END of the string?

Note that I heard of write.fwf from the gdata package which is really nice but doesn't help much in this case, because I need to write a very specific non-standard format for an outdated old program.


回答1:


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




回答2:


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.




回答3:


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   "


来源:https://stackoverflow.com/questions/9261961/how-to-use-rs-sprintf-to-create-fixed-width-strings-with-fill-whitespace-at-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!