R if-else not working [duplicate] - r

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

Related

R: Object not found inside a user-defined function, and unexpected {

I have a function with one argument that's supposed to be a 3-column data-frame.
probfinal<-function(y){
x<-c(0,1,3)
prev<-numeric(20)
for(i in 1:length(y[,1]){
prev[i]<-y[i,3]+sum(sample(x,38-y[i,2],replace=TRUE,prob=c(0.4,0.2,0.4)))
}
ligprev<-cbind(y,prev)
return(ligprev)
}
I have two errors:
Error: unexpected '{' in:
" prev<-numeric(20)
for(i in 1:length(y[,1]){"
and
Error: object 'y' not found
And then other errors related to the mentioned ones.
Where's the problem?
Thanks
Your function is missing a bracket:
probfinal<-function(y){
x<-c(0,1,3)
prev<-numeric(20)
for(i in 1:length(y[,1])**)**{
prev[i]<-y[i,3]+sum(sample(x,38-y[i,2],replace=TRUE,prob=c(0.4,0.2,0.4)))
}
ligprev<-cbind(y,prev)
return(ligprev)
}
I marked it with two asterisks

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),]) {
...
}

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-Project if else syntax [duplicate]

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?

unexpected ')', which I can not figure out

I am getting the following error. I can not figure out what is missing, as I seem to have all my brackets matched up.
Error: unexpected ')' in:
"{
if (grepl(propertiesData[x,'city'],population[z,'NAME'],ignore.case=TRUE) & (propertiesData[x,'stateLong']==population[z,'STATENAME')"
Here is the code of the loop:
for (z in c(1:nrow(population)))
{
if (grepl(propertiesData[x,'city'],population[z,'NAME'],ignore.case=TRUE) & (propertiesData[x,'stateLong']==population[z,'STATENAME'))
{
propertiesData[x,'population']=population[z,'POP_2009']
break
}
}
==population[z,'STATENAME'))
Seems like you forgot the closing bracket. Add it in and see what happens:
==population[z,'STATENAME']))
You're missing one ] at the end of line.
...==population[z,'STATENAME'] ))
You are missing "]" at the end : (propertiesData[x,'stateLong']==population[z,'STATENAME']))

Resources