有没有一种方法可以在R函数内循环?

时间:2020-10-02 04:21:38

标签: r function loops

我在尝试创建一个函数时遇到麻烦。我想将数字转换为一周中分配的天数。例如:1 =“星期一”,2 =“星期二”,3 =“星期三”,4 =“星期四”,5 =“星期五”,6 =“星期六”,0 =“星期日”

下面是我写函数的尝试,但出现错误,并且我还认为必须有一种循环该函数的方法。我就是不知道。

#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 个答案:

答案 0 :(得分:1)

我在这里使用case_when包中的dplyr,而只是让您的函数将输入映射到某些字符串输出。

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

答案 1 :(得分:1)

您可以创建向量并将其子集化:

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"