Weird Behaviour in R if else Statement - r

I'm quit new to R programming. While I was trying to write my first if else statement I came across a weird behaviour which I don't understand.
When I run below code:
x = 4;
y=4;
if (x==y) {
print('they are equal');
} else {
print('they are not equal');
}
I get no error and I get the expected output. However when I change the indentation of the same exact code as below:
if(x==y){print('they are equal');}
else{print('they are not equal');}
I get an error message saying that 'Error: unexpected 'else' in "else"'.
So does this means that R is an indentation sensitive language like Python?

To my limited experience, in R syntex, else statement should start from the same line where if statement ends. Otherwise, it won't work. And R is NOT indenting sensitive. For example,
This will work
if(x==y){print('they are equal')
} else
{print('they are not equal')}
[1] "they are equal"
Even this will work
if(x==y){print('they are equal')} else
{print('they are not equal')}
[1] "they are equal"
This will also work
if(x==y){print('they are equal')} else {print('they are not equal')}
[1] "they are equal"
But the code you have written doesn't work because else statement doesn't start from the same line where if statement ends. Another example would be,
This won't work
if(x==y){print('they are equal')}
else {
print('they are not equal')}
Also, you don't need the semi-colons.

Related

Using audio_play_sound() in a if statement GameMaker

I am trying to use the command:
audio_play_sound()
I am trying to insert it into this piece of code, so that when the player jumps, a sound plays.
if (key_jump) && (jumps > 0)
{
jumps -=1;
vsp = -jumpspeed;
}
Code that causes problem:
if (key_jump) && (jumps > 0)
{
jumps -=1;
vsp = -jumpspeed;
audio_play_sound(snd_jump)
}
Simply inserting the line into the if statement does not work, and gives the error WRONG NUMBER OF ARGUMENTS IN FUNCTION. This is rather confusing, perhaps I am using the wrong command? Thanks in advance
The problem is stated in the error, you're providing the wrong number of arguments to the audo_play_sound function.
from the docs
audio_play_sound(index, priority, loop);
As the person above states your answer is audio_play_sound(snd_jump, 1, false).

Incorrect Output If then Else statement in R

Please see the code below. the code does not show the accurate value as everything it being set to "Others" in the new var titles:
extractTitle<- function(name){
name<-as.character(name)
if (length(grep("Miss.",name))>0){
return("Miss.")
}else if (length(grep("Master.",name))>0){
return("Master.")
}else if (length(grep("Mrs.",name))>0){
return("Mrs.")
}else if (length(grep("Mr.",name))>0){
return("Mr.")
}else {
return("Other")
}
}
titles<- NULL
for (i in 1:nrow(data.combined)){
titles<- c(titles,extractTitle(data.combined[i,"name"]))
}
data.combined$title<- as.factor(titles)
Kindly advice where is the issue.
Your code works for me when trying it with simple test data ("foobar", "fooMaster.bar" "Master.bar", "fooMaster.", etc.). So the issue probably lies with how you handle the dataset to the function. For example, if you misspelled the "name" column access this will handle NULL to the function, which in turn will cause "Other" be handed back.
PS: sorry for posting this as an answer but I'm still too low for comments :)

R: Is there a function like at_exit in the Ruby?

I want do something before exit the R program, just like in the Ruby we can do:
at_exit do
print "before exit"
end
The on.exit in R, will do something before exit current function, but cannot work for whole program.
I've searched online, but cannot find useful info.
According to hrbrmstr's advice, I've tried .Last and reg.finalizer and they work. This is the summary:
Using .Last variable
.Last <- function() {
cat("at last\n")
}
cat("ok\n")
The result will be:
[1] "ok"
at last
Using reg.finalizer function
reg.finalizer(environment(),
function(e) cat("at last\n"),
onexit=TRUE)
The result will be:
NULL
[1] "ok"
at last

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