5

I'm working through a tutorial and am having a tough time on syntax. I cannot see where I'm going wrong but I'm getting error messages from the console.

I have a list of 300 csv files in a directory. A user would input the number (id) of the file they are seeking info on. The format is like so: 001.csv, 002.csv, 090.csv 250.csv etc etc.

The function is to convert the input into a string that is the csv file name. e.g. if id is 5, return 005.csv. If the input in 220, output 220.csv.

Here is the code:

csvfile <- function(id) {
  if (id < 10) { paste0(0,0,id,".csv"
  } else if (id < 100) {paste0(0,id,".csv"
  }else paste0(id,".csv")
}

Here is the error that the console returns:

> csvfile <- function(id) {
+ if (id < 10) { paste0(0,0,id,".csv"
+ } else if (id < 100) {paste0(0,id,".csv"
Error: unexpected '}' in:
"if (id < 10) { paste0(0,0,id,".csv"
}"
> }else paste0(id,".csv")
Error: unexpected '}' in "}"
> }

I can see R is not liking some of my '}' but cannot figure out why? What's wrong with my syntax?

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
Doug Fir
  • 19,971
  • 47
  • 169
  • 299
  • 5
    There is already a function that very nicely does what your function aims at doing: `sprintf("%03d.csv", id)`. E.g. if you give it `id=14` it returns `"014.csv"`. – Backlin Jan 15 '13 at 14:30
  • 1
    @Backlin But here the OP is going through a tutorial...maybe he needs more help on how to correct syntax errors.. – agstudy Jan 15 '13 at 14:33
  • Yes, that's why I commented and not replied. Just like to mention that there are tonnes of small functions in R that takes care of (pardon my choice of words) trivial tasks like this. As a beginner I wrote lots of my own custom made little functions, but as I progressed and discovored the "right" way of doing things I have discarded most of them. – Backlin Jan 15 '13 at 14:39

2 Answers2

19

You're missing some ) characters in there, for the first two paste0 calls:

csvfile <- function(id) {
    if (id < 10) { 
        paste0(0,0,id,".csv")
    } else if (id < 100) {
        paste0(0,id,".csv")
    } else paste0(id,".csv")
}
Romain Francois
  • 17,432
  • 3
  • 51
  • 77
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
7

Syntax error in R are hard to find in the beginning. Console is good to test one line code but it is not very helpful when you try to write longer statements.

My advise is to use an IDE to help you to write functions. why not to try RStudio for example?

agstudy
  • 119,832
  • 17
  • 199
  • 261