Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a number with leading zeroes to function

Tags:

r

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?

like image 522
user1471980 Avatar asked Jan 13 '13 19:01

user1471980


People also ask

How do you format a number with leading zeros?

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.

What is the rule for leading zeros?

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.

How do you keep the leading zeros in a formula bar?

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.

How can I pad a value with leading zeros?

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.


2 Answers

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> 
like image 142
Dirk Eddelbuettel Avatar answered Sep 30 '22 07:09

Dirk Eddelbuettel


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"
like image 42
flodel Avatar answered Sep 30 '22 08:09

flodel