R-Project if else syntax [duplicate] - r

This question already has answers here:
Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code
(3 answers)
Closed 8 years ago.
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?

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?

Related

Terminate the exectuion with STOP() but not throwing an "Error" message in R [duplicate]

This question already has answers here:
Stop an R program without error
(12 answers)
Closed 4 years ago.
I want a function that would terminate the program when there is no data are returned and print out a message to users about there is no new data are found.
However, I don't want my function throws users an "error" message. For example,
my_update_function <- function () {
df <- data # get data
if (nrow(df) == 0) {
stop('\r no new data found')
}
else {
# do some updates
}
}
current output:
Error in my_update_function() :
no new data found
my expected output: no new data found
How can I get rid of the "Error" in my output message but the program is terminated when the condition is true.
This would hide the word "error" on the console but the program still sees it as an error. Referencing on Stop an R program without error
if (nrow(new_data) == 0) {
message(log_date, " - ","no new_data is found ")
opt <- options(show.error.messages=FALSE)
on.exit(options(opt))
stop()
}
else { # DO SOMETHING ELSE
}

R Error in if-nest and/or for-loop? Unexpected '}' in "}"

I'm trying to work with a table called 'data' in R.
My code is roughly like this:
for (i in nrow(data):1) {
data$meanApproval[i] = mean(data[max(1,i-11):i,5])
if(data$Poll = data[duplicated(data$Poll),]) {
data = data[!duplicated(data$Poll),]
}
}
It throws the error as in the title:
"Unexpected '}' in "}""
The syntax before I added this code gave no complaint, so I'm sure it's the section I've posted.
I know this may be considered a duplicate question, but I've studied all the other answers, and none of them help me with this issue. I can't find any missing bracket matches, and none of these are the result of a unicode misread.
Any help would be greatly appreciated.
The error message was misleading from the actual error in the code.
if(data$Poll = data[duplicated(data$Poll),]) {
...
}
should have read == for the if check
if(data$Poll == data[duplicated(data$Poll),]) {
...
}

How to create a loop function that will create data frames by using different sql queries

I try to create a loop that will create data frames by using different sql queries that have the same name exept the day number.For example here is the name for query that is for day 1 :SF_2013_Day1_BaseLine and this is for day 6: SF_2013_Day6_BaseLine. I wrote this code (below) but I got an error : Error: unexpected ',' in "for(i in 3," .So any Idea how can i get this code to work ?
Thank you
for (i in 1,3,6,10,14,21,30) {
SF_FinalviewQ3_2013_Day[i]_BaseLine<-sqlQuery(DB,"select * from [SF_2013_Day[i]_BaseLine]");
dim(SF_Day[i]_BaseLine)}
After a change based on #Pgibas edvice to this code :
for (i in c(1,3,6,10,14,21,30)) {
SF_FinalviewQ3_2013_Day[i]_BaseLine<-sqlQuery(DB,"select * from [SF_2013_Day[i]_BaseLine]");
dim(SF_Day[i]_BaseLine)}
I got this error: Error: unexpected input in "for(i in c(3,6)){glm_d[i]_" . What can I do to resolve the problem?
You need to resolve i within the names first:
for (i in c(1,3,6,10,14,21,30)) {
set <- sqlQuery(DB, paste0("select * from [SF_2013_Day[", i, "]_BaseLine]"))
eval(parse(text = paste0("SF_FinalviewQ3_2013_Day", i, "_BaseLine <- set"))
dim(set)
}

using if/else with function in R

I have tried to write a simple code to compute the median but I got an error.
This is what I wrote
median<-function(x){odd.even<-length(x)%%2 if (odd.even = = 0)(sort(x)[length(x)/2]+sort(x)[1+length(x)/2])/2 else (sort(x)[ceiling(length(x)/2)])}
and this is the error I got
Error: unexpected 'if' in "median<-function(x){odd.even<-length(x)%%2 if"
Thanks
Try this (you forgot the brackets {)
median<-function(x){
odd.even<-length(x)%%2
if (odd.even == 0){
(sort(x)[length(x)/2]+sort(x)[1+length(x)/2])/2
} else {
(sort(x)[ceiling(length(x)/2)])
}
}
As pointed out if you want not to use bracket you can always do this, with a new line on the if statement :
median<-function(x){
odd.even<-length(x)%%2
if (odd.even == 0) (sort(x)[length(x)/2]+sort(x)[1+length(x)/2])/2 else (sort(x)[ceiling(length(x)/2)])
}
Also a return(x) at the end, might help the reading process, although it is not compulsory.

R if-else not working [duplicate]

This question already has answers here:
if/else constructs inside and outside functions
(2 answers)
Closed 10 years ago.
What is wrong with this if-else in my R program?
if(is.na(result)[1])
print("NA")
else
coef(result)[[1]]
I'm getting an error:
> if(is.na(result)[1])
+ print("NA")
> else
Error: unexpected 'else' in "else"
> coef(result)[[1]]
So then I added curly braces around the if and the else and now I get this error:
> if(is.na(result)[1]) {
+     print("NA")
Error: unexpected input in:
"if(is.na(result)[1]) {
¬"
> } else {
Error: unexpected '}' in "}"
>     coef(result)[[1]]
Error: unexpected input in "¬"
> }
Error: unexpected '}' in "}"
It is that you are lacking curly braces. Try
if(is.na(result)[1]) {
print("NA")
} else {
coef(result)[[1]]
}
This matters less when your source an entire file at once but for line-by-line parsing (eg when you enter at the prompt) you have to tell R that more code is coming.
I think your problem is signaled with this error message:
"if(is.na(result)[1]) {
¬"
Notice that strange little symbol? You have gotten a non-printing character that looks like one of those old IBM end-of-line markers. It could be problem with your LOCALE strings or with your keyboard mapping or with code you got off the Internet. Hard to tell, but you should definitely try to get rid of them by backspacing over them/
Without curly brackets, the if ... else ... construct should be on one line only:
if(is.na(result)[1]) print("NA") else coef(result)[[1]]
If you only have one condition and two results it's syntactically easier to use ifelse()
ifelse(is.na(result)[1],
print("NA"),
coef(result)[[1]]
)
This runs for me without errors
x <- 1:5
result <- lm(c(1:3,7,6) ~ x)
if(is.na(result)[1]) {
print("NA")
} else {
coef(result)[[1]]
}
and produces
[1] -0.7

Resources