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?
In R, an if-else statement tells the program to run one block of code if the conditional statement is TRUE , and a different block of code if it is FALSE .
We will use nested if else statement to check this. First, we check that out of the three numbers, whether the first two are equal. If they are, then we go inside the nested if to check whether the third is equal to them. If yes, then all are equal else they are not equal.
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")
}
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?
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