using if/else with function in R - 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.

Related

Create functions in R

I'm fairly new to R and I have not been working with functions in R before.
I want to write a program/algorithm (using R) that calculates the square root of a given positive number.
Would anyone mind take the time to give me an example of how this can be achieved?
Thanks a lot in advance!
UPDATE
posNum_to_squaRtNum <- function(posNum) {
if (posNum <= 0)
print("Due to mathmatical principles you have to input a positive number")
else
squaRtNum <- sqrt(posNum)
return(squaRtNum)
}
When I insert a negative number in the function, the output is my print PLUS the error: "Error in posNum_to_squaRtNum(-1) : object 'squaRtNum' not found." It should not go on to the else statement, if the if statement is fulfilled right?
You should wrap your if conditions in brackets:
posNum_to_squaRtNum <- function(posNum) {
if (posNum <= 0) {
print("Due to mathmatical principles you have to input a positive number")
} else {
squaRtNum <- sqrt(posNum)
return(squaRtNum)
}
}

Weird Behaviour in R if else Statement

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.

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).

why R generating error when i try to pass argument to the if function

here i am giving the code
#my user defined function
my.display<-function(x,display=TRUE,type="hist",prob=TRUE)
{
if(display=TRUE)
print("1")
else hist(x)
if(type=hist) hist(x) elseif(type=density) plot(density(x))
cat("Please specify type as either hist or density")
if(prob=TRUE) hist(x,freq=TRUE) else hist(x,freq=TRUE)
}
the error r shows is when it passes to the if(display=TRUE), I believe the expression is wrong or something. if the display=TRUE argument then it should print 1 else generate a histogram of the vector x.
if(type=hist) also showing error . someone please help.
= acts as assign operator same as <- operator in R
while == is a logical operator.
So you should use if(display == TRUE). You might also want to add some {} in your if-else structures for readability.
Try this code for second doubt
updated:
my.display<-function(x,display,type,prob=TRUE)
{if(display==TRUE){
print("1")
}
else
if(type=="hist") {hist(x)}
else
if(type=="density") {plot(density(x))}
else
cat("Please specify type as either hist or density")
if(prob==TRUE){ hist(x,freq=TRUE)}
else
hist(x,freq=TRUE)
}

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 :)

Resources