Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

r

In .NET, I can use string.PadLeft() and string.PadRight() to pad 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 is the equivalent in R?

like image 747
Contango Avatar asked Dec 02 '22 20:12

Contango


1 Answers

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, like .NET, the number specified is the total width that we want to fit our text into.

like image 82
Contango Avatar answered Dec 04 '22 10:12

Contango