【发布时间】:2012-11-09 07:22:05
【问题描述】:
我正在制作一个输出星期几的函数,给定自 1970 年 1 月 1 日以来的天数。当它是if then 语句链时,该函数运行良好,但我想在向量上使用该函数,所以我需要构建这个看起来很傻的ifelse 语句链。
不幸的是,我不断收到此错误:
Error in ifelse(rem == 0, day = "Thursday", ifelse(rem == 1, day = "Friday", :
unused argument(s) (day = "Thursday")
Calls: dayFinder -> ifelse
Execution halted
我无法弄清楚如何绕过它 - 看起来它只是忽略了 ifelse 语句的 then 部分。我尝试向它提供各种样本数据集或数据点,但无法修复错误。
这是我的代码 - 在此先感谢。
dayFinder <- function(x){
#Assuming that '0' refers to January 1 1970
#Store given number
start <- x
#Initialize variable
day="Halloween"
#Divide x by 7 and store remainder
rem <- x%%7
#Determine the day
ifelse(rem==0, day="Thursday",
ifelse (rem==1, day="Friday",
ifelse (rem==2, day="Saturday",
ifelse (rem==3, day="Sunday",
ifelse (rem==4, day="Monday",
ifelse(rem==5, day="Tuesday",
if (rem==6)
{
day="Wednesday"
}))))))
return(day)
}
q = seq(7,50,1)
z = dayFinder(q)
z
【问题讨论】:
-
看到这个了吗? Find the day of a week in R。将您的天数值转换为可以输入
weekdays的真实日期值应该很简单。一般来说,如果有一个基本函数可以满足你的需要,那么它可能比你或我写的要仔细得多。 -
当他们在 thedailywtf 一遍又一遍地写作时,如果你想执行一些显而易见的任务,可以肯定其他人已经这样做了。因此,在常见的 R 包中搜索日期/时间函数相对容易:-)
标签: r if-statement