在 .NET 中,我可以使用 string.PadLeft() string.PadRight() 在左边/右边用空格填充字符串。

var myString = "test";
Console.WriteLine(myString.PadLeft(10)); //prints "      test"
Console.WriteLine(myString.PadLeft(2)); //prints "test"
Console.WriteLine(myString.PadLeft(10, '.')); //prints "......test"
Console.WriteLine(myString.PadRight(10, '.')); //prints "test......"

R中的等价物是什么?

最佳答案

您可以将长度作为参数传入:

PadLeft <- function(s, x) {
  require(stringr)
  sprintf("%*s", x+str_length(s), s)
}

PadRight <- function(s, x) {
  require(stringr)
  sprintf("%*s", -str_length(s)-x, s)
}

PadLeft("hello", 3)
## [1] "   hello"
PadRight("hello", 3)
## [1] "hello   "

关于c# - .NET 中 PadLeft() 和 PadRight() 的 R 等价物是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14686653/

10-09 07:17