我正在尝试以编程方式将字符串宽度值插入到 sprintf()
格式中。
想要的结果是
sprintf("%-20s", "hello")
# [1] "hello "
但我想在同一个调用中即时插入
20
,以便它可以是任何数字。我试过了sprintf("%%-%ds", 20, "hello")
# [1] "%-20s"
sprintf("%-%ds", 20, "hello")
# Error in sprintf("%-%ds", 20, "hello") :
# invalid format '%-%d'; use format %f, %e, %g or %a for numeric objects
sprintf("%-%%ds", 20, "hello")
# Error in sprintf("%-%%ds", 20, "hello") :
# invalid format '%-%%d'; use format %f, %e, %g or %a for numeric objects
这在
sprintf()
中可能吗? 最佳答案
是的,这可以通过使用星号 *
来实现。
如前所述 in the docs ,
因此代码将是
> sprintf("%-*s", 20, "hello")
[1] "hello "
关于r - 以编程方式将字符串宽度值插入 sprintf(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39536711/