如何完善R语言函数实现指定日期是否存在于Test数据库的判断
R日期校验函数修正方案
完整可运行代码
# 测试数据集 Test <- structure( list(dat= c("2021-01-01","2021-01-02","2021-01-03"), X= c(5,4,0)), class = "data.frame", row.names = c(NA, -3L)) # 修正后的校验函数(英文提示) firstf <- function(input_date) { if (!input_date %in% Test$dat) { print("This date is not in your Test database") } else { print("This date is in your Test database") } }
主要修改点
- 新增
input_date形参,用于接收外部传入的日期参数 - 用
%in%运算符判断传入日期是否存在于Test数据集的dat列中,!代表逻辑取反 - 补全原代码中未闭合的双引号
运行效果
- 执行
firstf("2021-01-01"),返回结果:"This date is in your Test database" - 执行
firstf("2021-01-15"),返回结果:"This date is not in your Test database"
中文提示版本
如果需要输出中文提示,替换函数逻辑即可:
firstf <- function(input_date) { if (!input_date %in% Test$dat) { print("该日期不存在于你的Test数据库中") } else { print("该日期存在于你的Test数据库中") } }
内容的提问来源于stack exchange,提问作者user17163779
相关产品推荐
相关产品推荐

