Reputation: 948
I'm starting with R. I've taken a 2d sample in a list. This list contains 2 vectors with 100 elements either one:
muestra2d <- take_samples(2, 100, c(-100, 100));
I've a function that calculates coefficients m and b of a line in the form y=mx+b
in a box in a given range.
vars <- sim_line(c(-100, 100))
Ok, my aim is apply a function f(x,y)=y-ax-b
where x
is an element of muestra2d[1]
, y
is an element of muestra2d[2]
, a
is the slope of the line (m) and b
is the offset of the line. The function must label the sample with the sign of the function for each pair of values (x,y).
I've tried it with this line
result <- lapply(muestra2d, function(x,y) (y-(vars[5]*x)-vars[6]))
thinking lapply takes an element from the first vector of the list and copies it in x
, doing the same for y
and applying the function to this values, but it isn't a good idea.
How I can do this? How I can plot the line, points and negative points with another color at the same time?
Upvotes: 0
Views: 210
Reputation: 35324
set.seed(1L);
take_samples <- function(sample.num,elem.num,box) lapply(seq_len(sample.num),function(i) runif(elem.num,box[1L],box[2L]));
sim_line <- function(box) c(1,0);
box <- c(-100,100);
muestra2d <- take_samples(2L,100L,box);
vars <- sim_line(box);
signs <- sign(muestra2d[[2L]] - vars[1L]*muestra2d[[1L]] - vars[2L]);
par(xaxs='i',yaxs='i');
plot(NA,xlim=box,ylim=box,xlab='x',ylab='y',main='plot');
abline(vars[2L],vars[1L]);
with(setNames(muestra2d,c('x','y')),{
points(x[signs>=0],y[signs>=0],col='green');
points(x[signs<0],y[signs<0],col='red');
});
Upvotes: 1