我有一个简单的函数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
答案 0 :(得分:4)
必须对plot.function
的函数进行矢量化。尝试
plot(Vectorize(A), 2,10)
编辑:如果你的函数有很多参数,你想保持其他参数不变,请使用:
plot(Vectorize(function(s) C(s, SPP="SA")), 2,10)