I am trying to write a function that has an argument like below:
myfunction<-function(id){
print(paste(id, ".", "csv", sep=""))
}
when the id value is like this 009, it prints it as 9.csv not 009.csv.
I tried this:
id<-as.character(id)
this is not working. Any suggestions?
Select the cell or range of cells that you want to format. Press Ctrl+1 to load the Format Cells dialog. Select the Number tab, then in the Category list, click Custom and then, in the Type box, type the number format, such as 000-00-0000 for a social security number code, or 00000 for a five-digit postal code.
1) Leading zeroes shall be suppressed, although a single zero before a decimal point is allowed. 2) Significant zeroes shall not be suppressed; when a single zero is significant, it may be used. 3) Do not include Trailing zeroes after the decimal point unless they are needed to indicate precision.
Method 1 - Add Apostrophe The first way to keep leading zeros in front of numbers is to put an apostrophe ' in front of the number. Notice how I input '0123 and not just 0123. Now, when I hit Enter, the number will keep its leading zero. In the cell, all we see is the number; the apostrophe has become invisible.
To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.
Use e.g. sprintf()
:
myfunction <- function(id) {
sprintf("%03d.csv", id)
}
which gives
R> cat(myfunction(9), "\n")
009.csv
R> cat(myfunction(199), "\n")
199.csv
R>
Although you already accepted @Dirk's answer...
The problem is you are passing your input as a numeric. For R, 009
evaluates to 9
:
> 009
[1] 9
so when you run myfunction(009)
, it really runs myfunction(9)
. It should be no surprise you get "9.csv" as your output.
Instead, you should pass your input as a character: "009":
> myfunction("009")
[1] "009.csv"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With