Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R-Project if else syntax [duplicate]

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?

like image 936
Doug Fir Avatar asked Jan 15 '13 14:01

Doug Fir


People also ask

What is if else statement in R?

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 .

How does nested if else work?

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.


2 Answers

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")
}
like image 194
Matthew Lundberg Avatar answered Oct 04 '22 15:10

Matthew Lundberg


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?

like image 32
agstudy Avatar answered Oct 04 '22 15:10

agstudy