0

I am having trouble with a function I am trying to create. I want to convert numbers into assigned days of the week. For example: 1='Monday', 2='Tuesday', 3='Wednesday', 4='Thursday', 5='Friday', 6='Saturday', 0='Sunday'

Below is my attempt a writing the function, but I get an error, and I also think there must be a way to loop it. I just don't know how.

#experiment
pow <- function(x) {
   
 if (x == 1)

    {

    print("Monday")  

    }

    else if (x == 2)

    {

    print("Tuesday")

    } 

    else if (x == 3)

    {
    print("Wednesday")
    } 
    else if (x == 4)
    {
    print("Thursday")
    } 
    else if (x == 5)
    {
    print("Friday")
    } 
    else if (x == 6)
    {
    print("Saturday")
    } 
    else if (x == 0)
    {
    print("Sunday")
    } 
    else if (is.na(x) ==TRUE)
     {print("Sorry, please enter two numbers.")
    }
}

2 Answers 2

1

I would use case_when here from the dplyr package, and instead would just have your function map an input to some string output.

library(dplyr)

pow <- function(x) {
    output = case_when(
        x == 0 ~ "Sunday",
        x == 1 ~ "Monday",
        x == 2 ~ "Tuesday",
        x == 3 ~ "Wednesday",
        x == 4 ~ "Thursday",
        x == 5 ~ "Friday",
        x == 6 ~ "Saturday",
        TRUE ~ "Sorry, please enter two numbers."
    )

    return(output)
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a vector and subset it :

pow <- function(x) {
  days <- c('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
  days[x + 1]
}

pow(2)
#[1] "Tuesday"
pow(0)
#[1] "Sunday"

#You can also pass more than 1 number to the function
pow(c(1, 5, 6, NA, 3))
#[1] "Monday"    "Friday"    "Saturday"  NA     "Wednesday"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.