全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 R语言论坛
8193 2
2015-08-12
悬赏 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的值就明白了
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2015-8-12 14:50:33
循环运行到a=3时候,location长度只有3,location[a+1]不存在所以报错

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

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

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

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

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

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群