2つの関数(2x + 1と3x - 0.5 * x^2)のグラフを同じグラフシートにプロットしようとしましたが、2つの異なる範囲(x < = 3、x> 3)。これまでのところ、私は次のように2つの関数を定義している:私は、コードを実行すると2つの関数のグラフをプロットするR
# Define first function with given range
Line1 <- function(x) {
if (x <= 3) {
(3*x) + 1 } else {
}
}
# Define second function with given range
Line2 <- function(x) {
if (x > 3) {
2*x - (0.5*(x^2)) } else {
}
}
# Plot functions
ggplot(d,aes(x=x)) + stat_function(fun=rwrap(Line1,0,3),geom="line",col="blue")
+ stat_function(fun=rwrap(Line2,3,5),geom="line",col="red")`
、私は次のエラーメッセージが出ます:
Error: Discrete value supplied to continuous scale In addition:
Warning messages:
1: In if (x <= 3) { : the condition has length > 1 and only the first element will be used
2: In if (x > 3) { : the condition has length > 1 and only the first element will be used
私はそれをトラブルシューティングしようとしたが、私はちょうど失われていますこの時点で。
コードが引用されているのはなぜですか? – Gregor
問題は、関数がベクトル化されていないということです。それらはat時には 'x'の単一の値で動作しますが、' Line1(0:10) 'は動作しません。 ifelse(x <= 3,3 * x + 1,2 * x - 0.5 * x)のベクトル化されたバージョンとして 'ifelse'を使って単一の関数にしてください。^2) '。 – Gregor
引用して申し訳ありませんが、私はコピーアンドペーストのプロセスを間違えました。私はあなたのifelseステートメントを理解しました。しかし、どのように色を変えて線をプロットするのですか? – user8550070