3

我有一个简单的功能 A

A<-function(s){
  c0=360
  c1=60
  c2=30
  k=10
(8/60)*(c0+(sum(k*(c1+c2*(1:(s-1))))))
}

我尝试绘制 A 但收到一条错误消息,这显然与函数中的 1:(s-1) 有关

> plot(A, 2,10)
Error in curve(expr = x, from = from, to = to, xlim = xlim, ylab = ylab,  : 
  'expr' did not evaluate to an object of length 'n'
In addition: Warning message:
In 1:(s - 1) : numerical expression has 101 elements: only the first used

它也发生在我的其他包含 for 循环的函数中,例如。for (i in 1:s). 我认为他们有类似的问题。

我可以用 A(2)...A(10) 手动创建一个列表,然后绘制它。但肯定有办法解决它,但我只是不知道如何。

谢谢。

-------更新:带有for循环的函数---------------

C<-function(s, SPP){
  selector<-allmeans$spp==SPP       ###allmeans is a data matrix
  meansofspp<-allmeans[selector,]
  result.list<-list()
  for (i in 1:s){
  deltap<-((meansofspp$p[i+1])-(meansofspp$p[i]))
  result.list<-append(result.list, deltap)
  }
  return(sum(unlist(result.list)))
  }

SPP接受诸如“OV”、“SA”之类的字符串.....

仅供参考,矩阵的一个例子

>meansofspp<-allmeans[selector,]
>selector<-allmeans$spp=="SA"
>meansofspp<-allmeans[selector,]
>meansofspp
                           Station spp          p       Psi       se_p     se_Psi
11                               1  SA 0.06805432 0.8258379 0.04033442 0.02424016
21                               2  SA 0.08564783 0.7610201 0.04822488 0.04585892
31                               3  SA 0.09324792 0.7400703 0.05057707 0.06107310
41                               4  SA 0.10526517 0.6976201 0.05539305 0.08971556
51                               5  SA 0.11531421 0.6631891 0.05931863 0.12450045
61                               6  SA 0.12277445 0.6415915 0.06208516 0.16334959
71                               7  SA 0.12762431 0.6341937 0.06323868 0.19052386
81                               8  SA 0.13125741 0.6404024 0.06478704 0.24361789
SA_99_new.p.dot                  9  SA 0.13300380 0.6578759 0.06518710 0.28016660


> C(1,"SA")
[1] 0.01759351
> plot(Vectorize(C), 1, 10, "SA")
Error in seq.int(from, to, length.out = n) : 'from' must be finite
In addition: Warning message:
In curve(expr = x, from = from, to = to, xlim = xlim, ylab = ylab,  :
  NAs introduced by coercion
4

1 回答 1

4

plot.function必须对函数进行矢量化。尝试

plot(Vectorize(A), 2,10)

编辑:如果你的函数有很多参数并且你想保持其他的固定,使用这个:

plot(Vectorize(function(s) C(s, SPP="SA")), 2,10)
于 2013-05-15T18:12:54.327 回答