2013-05-15 38 views
3

我有一个简单的功能的[R绘制包含序列/列表

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 

它也发生在我的包含循环,EX等功能。 for (i in 1:s)。我认为他们有类似的问题。

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

谢谢。

-------更新:功能与循环---------------------------

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” .....

FYI,基质

>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

plot.function函数必须被矢量的例子。尝试

plot(Vectorize(A), 2,10) 

编辑:如果函数有很多争论,你要保持固定的人,用这个:

plot(Vectorize(function(s) C(s, SPP="SA")), 2,10) 
+0

我看到,它的工作!非常感谢。 – lamushidi

+0

但它不适用于包含“for(i in 1:s)”的函数,为什么? – lamushidi

+0

它应该工作。你能用循环和错误信息发布你的函数吗? –