I'm following this tutorial to implement a support vector machine in R.
I'm having trouble clarifying the working of the plot command
plot(x,col=ifelse(y>0,1,2))
x is of size 300 as length(x)
confirms, but length(ifelse(y>0,1,2)
shows 150.
How is the plot working then, if there are 300 x values but only 150 y values?
When I tried
plot(x,ifelse(y>0,1,2))
it shows the expected error ie,
Error in xy.coords(x, y, xlabel, ylabel, log) :
'x' and 'y' lengths differ
What is it about col=ifelse(y>0,1,2)
that makes it work?
Generally, R knows recycling, ie in many situations R recycles vectors if they have not the required length, eg
1:4 + 1:2
The vector 1:2
is recycled, so effectively it becomes c(1,2,1,2)
to fit the length of the other vector. Now, we can sum the vectors
c(1,2,3,4) + c(1,2,1,2)
The same happens in your example for the col
argument. The vector col
is recycled so it fits the length of x
. But as you see, not all argument values are always recycled automatically. In the case of the x
and y
argument in plot
this is not the case. This makes sense as it is probably an error, if the length of these two vectors do not match.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.