kpie
kpie

Reputation: 11080

Plotting a constant function in R with curve()

so I have an error...

f <- function(x){return(1)}
curve(f(x),0,100,xname="x")

Error in curve(f(x), 0, 100, xname = "x") : 
'expr' did not evaluate to an object of length 'n'

Which is strange considering that

F <- function(x){return(0*x+1)}
curve(F(x),0,100,xname="x")

Works just fine... This informed me to think about how R treats data.frame()s.

a <- data.frame(1,2,3)
f(a)
# [1] 1
F(a)
#   X1 X2 X3
# 1  1  1  1

Meaning that the Function Vectorize() will fix my problem. Irregardless this is an acute example of the implicit decisions That R makes, which result in inconsistent behavior.

Upvotes: 1

Views: 2600

Answers (1)

akond
akond

Reputation: 16035

The problem is the function should return a vector of the same length as a parameter. In your case instead of n, the function always returns a vector of just one. The solution could be

 f <- function(x){return(rep(1,length(x)))}

Upvotes: 2

Related Questions