请,我正在尝试根据用户的输入来打印消息。 我正在研究测试,我想创建一个函数,如果我键入特定文章(可变字符),它将检查一组向量并打印一条消息。
ExpfromUS <- function(x){
x <- readline("Check if your articles could be import or export to US. Entry the type of article that you want to ship: ")
a <- c(x == CBOExUS)
b <- c(x == RQSVExUS)
e <- c(x == NATExUS)
for ( i in length(a == TRUE)){
if (a[i] == TRUE){
print("Ok, but just with Contractual basis only");
break; }
else{ for (i in length(b)){
if (b[i] == TRUE){
print("Ok, but with restrictions of quantity, size or value");
break;}
else{ for (i in length(c)){
if (e[i] == TRUE){
print("Sorry, but we are not able to ship your cargo at this moment");
break;}
else{ print("Please check your entry we could not find this article in our database")
}}
}
}
}
}
}
但是总是打印最后一条消息“请检查您的输入,我们在数据库中找不到此文章”,我在做什么错? (对不起,这是初学者的疑问)。 感谢所有花时间帮助我的人。
答案 0 :(得分:0)
扩大我的评论:我怀疑您为所有for
循环建立索引是(部分)问题。当前的索引只会引起一次迭代,因为length(a == TRUE)
将返回一个整数。我怀疑您想要其中“ a == TRUE”的数值,以便可以在该行输出消息。 which
函数返回与逻辑向量的“ TRUE”值的索引相对应的数字值,所以也许您想要:
for ( i in which(a) ){
....}
else{ for (i in which(b)){
...}
else{ for (i in which(c)){
....}
进一步的注意:使用逻辑向量时,几乎不需要包含== TRUE
,并且当向量包含NA时,有时会返回意外结果,因为NA永远不会==
。
鉴于您提供的这三个向量的值,我现在认为应该是
{....
a <- x %in% CBOExUS # the c() not needed. This returns a logical vector
b <- x %in% RQSVExUS
e <- x %in% NATExUS
.....
通过%in%
函数可以测试多个值。 ==
函数询问是否存在完全相等,这显然不太可能。还有 still 可能是其他缺陷,但是我们 still 没有[MCVE],因此我们 still 无法提供经过测试的编码。