我正在尝试在R中构建一个函数,它表示范围为[0,1]的100Hz的方波和锯齿波。我试过这个:
squarewave <- function (t) {
# 0.01 == 100Hz(=2Pi) -> 1 Period of the Squarewave
# 0.005 == Pi -> Half Period of the Squarewave
# if t smaller than a half period -> 1
# if t greater or equal than half a period -> 0
if ((t %% 0.01) < 0.005)
return (1)
else if ((t %% 0.01) >= 0.005)
return (0)
}
当我尝试用以下函数绘制此函数时:
plot(squarewave)
我收到以下错误:
> plot(squarewave)
Error in curve(expr = x, from = from, to = to, xlim = xlim, ylab = ylab, :
'expr' has not been evaluated to an object of length 'n'
In addition: Warning message:
In if ((t%%0.01) < 0.005) return(1) else if ((t%%0.01) >= 0.005) return(0) :
the condition has length > 1 and only the first element will be used
那为什么这不起作用?
答案 0 :(得分:2)
您需要将向量化函数传递给plot
。因此,要么使用Vectorize
自动执行此操作,要么使用ifelse
代替if
。
plot(Vectorize(squarewave))
或
squarewave2 <- function (t) {
# 0.01 == 100Hz(=2Pi) -> 1 Period of the Squarewave
# 0.005 == Pi -> Half Period of the Squarewave
# if t smaller than a half period -> 1
# if t greater or equal than half a period -> 0
ifelse(((t %% 0.01) < 0.005),1,0)
}
plot(squarewave2)
要提高plot
的分辨率,请使用参数n
,有关详细信息,请参阅?curve
。
答案 1 :(得分:0)
我最初错了,想要更新。
除非它已正确矢量化,否则无法绘制原始函数,而是需要绘制函数的输出。下面是使用您的特定功能执行此操作的简单方法。
sequence <- seq(from = 0,to = 0.01, by = 0.00001)
plot(sapply(X = sequence,FUN = squarewave),type = "o")