简体   繁体   English

将自己的函数应用于R中的列表

[英]Apply an own function to list in R

I'm starting with R. I've taken a 2d sample in a list. 我从R开始。我在列表中提取了2D样本。 This list contains 2 vectors with 100 elements either one: 此列表包含2个向量,其中包含100个元素,其中一个:

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. 我有一个函数,用于在给定范围内的框中以y=mx+b的形式计算线的系数m和b。

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. 好的,我的目标是应用函数f(x,y)=y-ax-b ,其中xmuestra2d[1]的元素, ymuestra2d[2]的元素, a是线的斜率(m ), b是该行的偏移量。 The function must label the sample with the sign of the function for each pair of values (x,y). 函数必须为每对值(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. 认为lapply从列表的第一个向量中获取一个元素并将其复制到x ,对y进行相同操作并将函数应用于该值,但这不是一个好主意。

How I can do this? 我该怎么做? How I can plot the line, points and negative points with another color at the same time? 如何同时绘制带有另一种颜色的线,点和负点?

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');
});

情节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM