I am very new to R and would like to know how a function is created.
Say if I have:
> colourName
[1] "red" "green" "blue" "yellow" "white" "black"
#Which the following colours equal something like this:
#red = 1
#green = 2
#blue = 3
#yellow = 4
#white = 5
#black = 6
How can I create a function called myColour() where the result is returned as a numeric vector?
So if I type the following below, I should get:
> myColour("yellow")
[1] 4
Please help..
My Code (but its wrong!)
colourName<-c("red", "green", "blue", "yellow", "white", "black")
data <- c(1,2,3,4,5,6)
myFunction <- function(colour){
colourName = data
return(colour)
}
myFunction("red")
Is there a possible way I can create it as a function?
You could lookup your colour(s) in a named vector, which you can do efficiently like so...
x <- setNames( seq_along( colourName ) , colourName )
#red green blue yellow white black
# 1 2 3 4 5 6
x[ 'red' ]
#red
# 1
Using a function here doesn't seem like a great thing to do, but if you wanted, you could have a simple lookup function like this, that takes a vector of colours and the lookup value (but you may as well just use which!!)...
myFunction <- function( colours , x){
y <- which( colours %in% x )
if( length(y) == 0L )
y <- "Colour not found"
return( y )
}
myFunction( colourName , "red")
[1] 1
# Using R's inbuilt colour names
myFunction( colours() , "purple")
[1] 547
Here's why your code is wrong, and what it does:
colourName<-c("red", "green", "blue", "yellow", "white", "black")
data <- c(1,2,3,4,5,6)
that sets two variables as vectors with those values.
myFunction <- function(colour){
that starts defining a new function with one parameter, colour.
colourName = data
that creates another new variable called colourName, (the single = sign is the same as the <- sign) and gives it the value of data. This colourName variable is only visible inside the function. So now you have a colourName variable in the function whose value is c(1,2,3,4,5,6) since its a copy of data from outside the function.
return(colour)
}
this returns the value of colour as the result of the function. Since this is the same as the parameter in myFunction <- function(colour){ and you've not changed the colour variable, you'll just get back what you put in!
myFunction("red")
This calls the function, setting the value of the argument colour to "red". Now go though the function code, and you should see that it will then print [1] "red" - a vector identical to the input.
I know this doesn't totally answer your question of how to get the number for the colour you want, but you've clearly not understood a lot of the basics of programming so I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With