R-Project if else syntax

I am working on a tutorial and have a hard syntax time. I do not see where I am mistaken, but I receive error messages from the console.

I have a list of 300 csv files in a directory. The user enters the number (id) of the file that is looking for information. The format is: 001.csv, 002.csv, 090.csv 250.csv, etc. Etc.

The function is to convert the input to a string, which is the name of the csv file. for example, if id is 5, return 005.csv. If the input is 220, the output is 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 returned by the console:

 > 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 see that some of my '}' do not like R, but cannot understand why? What is wrong with my syntax?

+4
source share
2 answers

You are missing characters ) there, for the first two calls to paste0 :

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

The syntax error in R is hard to find at the beginning. The console tests one line code well, but this is not very useful if you are trying to write longer statements.

I can recommend using an IDE to help you write functions. why not try RStudio for example?

+7
source

All Articles