What is the R equivalent for PadLeft () and PadRight () in .NET?

In .NET I can use string.PadLeft()

and string.PadRight()

to insert a string with spaces on the left / right.

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......"

      

What's the equivalent in R?

+3


source to share


3 answers


You can pass the length as a parameter:



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   "

      

+6


source


Use sprintf

which is built into R:

# Equivalent to .PadLeft.
sprintf("%7s", "hello") 
[1] "  hello"

# Equivalent to .PadRight.
sprintf("%-7s", "hello") 
[1] "hello  "

      



Note that, just like .NET, the number shown is the total width we want to put in our text.

+6


source


Use str_pad

from stringr

:

library(stringr)
str_pad("hello", 10)
str_pad("hello", 10, "right")
str_pad("hello", 10, "both")

      

+5


source







All Articles