楼主: yijiaobani
8250 2

[问答] R语言报错:Error in a1:a2 : NA/NaN argument [推广有奖]

  • 4关注
  • 5粉丝

已卖:69份资源

博士生

26%

还不是VIP/贵宾

-

威望
0
论坛币
191 个
通用积分
10.6711
学术水平
2 点
热心指数
8 点
信用等级
0 点
经验
5127 点
帖子
147
精华
0
在线时间
236 小时
注册时间
2015-5-18
最后登录
2020-10-28

楼主
yijiaobani 发表于 2015-8-12 14:50:32 |AI写论文
5论坛币
我编写一个函数,出现报错:

Error in a1:a2 : NA/NaN argument,没有结果。


我把函数提取出来,处理,也出现同样的报错,但是有结果。


我的问题:


1、为什么报错?


2、为什么程序可以运行出结果,但是编程函数调用就没有结果,什么情况?




程序如下:


to<- c("a",23,3,5,4,"a",23,"a")
c<- NULL
hello <- function(a){
  total<- a
  location <- grep("a",total)
  for(a in seq(location)){
  a1 <- (location[a]+1) # near the up  number
  a2 <- (location[a+1]-1) # near the down number
  for (b in (a1:a2)){
    c <- to[a]
  }
}
}
hello(to)

c


结果:

> hello(to)

Error in a1:a2 : NA/NaN argument

> c

NULL

这是调用函数的结果,c没有被处理,不明白。


单独运行程序:
to<- c("a",23,3,5,4,"a",23,"a")
c<- NULL
  total<- to
  location <- grep("a",total)
  for(a in seq(location)){
    a1 <- (location[a]+1) # near the up ck number
    a2 <- (location[a+1]-1) # near the down ck number
    for (b in (a1:a2)){
      c <- to[a]
    }
  }
c
结果如下:
>   for(a in seq(location)){ a1 <- (location[a]+1) # near the up ck number

     a2 <- (location[a+1]-1) # near the down ck number

    for (b in (a1:a2)){

       c <- to[a]

     }

   }

Error in a1:a2 : NA/NaN argument

> c[1] NA   "a"  "a"  "a"  "a"  NA   "23"

这里c是有结果的,也出现报错信息:NA/NaN argument

最佳答案

万人往LVR 查看完整内容

循环运行到a=3时候,location长度只有3,location[a+1]不存在所以报错 没明白程序哪里运行出结果了。 循环报错时,参数会停止在报错的位置,你看看a,b,c的值就明白了
关键词:argument Error MEN err R语言 Error argument
<img src="stati ...

沙发
万人往LVR 在职认证  发表于 2015-8-12 14:50:33
循环运行到a=3时候,location长度只有3,location[a+1]不存在所以报错

没明白程序哪里运行出结果了。

循环报错时,参数会停止在报错的位置,你看看a,b,c的值就明白了

藤椅
yijiaobani 发表于 2015-8-13 09:20:05
万人往LVR 发表于 2015-8-12 14:50
循环运行到a=3时候,location长度只有3,location[a+1]不存在所以报错

没明白程序哪里运行出结果了。
原来是这样的,location[4]不存在,所以报错了,十分感谢。

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2025-12-24 12:55