简体   繁体   English

有没有办法在 R 函数中循环?

[英]Is there a way to loop within an R function?

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'例如:1='星期一', 2='星期二', 3='星期三', 4='星期四', 5='星期五', 6='星期六', 0='星期日'

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

I would use case_when here from the dplyr package, and instead would just have your function map an input to some string output.我会在这里使用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)
}

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM