Find the coefficient which can minimize the difference between Y and one X I only have one variable Y which contains roughly 100 numbers in it, and there is a X has the same length as Y. Then, we use take the sum(Y) and sum(X).
Distance is defined as the difference between aX and Y, so simply make ax-Y close to 0. To make some clarifications, a is a number, X and Y are vectors with same length. The goal is to find an a such that aX= Y.
Here is my code:
lst =c()
for(a in seq(0.1,1,0.001)){
  a = c(sum(a * X)- sum(Y))
  lst = c(lst,a)
}

min(abs(lst)) #I only get the minimum, but I don't know how to get the correspond `a`

a is just a number, not like X and Y who have length equals to 100

$aX - Y = 0$ only for $X = Y/a$, in which case finding the value would be trivial since you can use basic arithmetic for that.
When there is no linear relationship between the two variables, or their relationship is noisy
$$
Y = aX + \varepsilon
$$
where $\varepsilon$ is a random noise term, this is not that simple. In such a case, what you are trying to achieve is to find such $a$ that minimizes some distance $d$ between the points. Since you have vectors, you would be minimizing a cost function that aggregates the distances between the points $c(aX,\,Y) = \sum_i d(aX_i,\,Y_i)$
$$
\operatorname{arg\,min}_a \,c(aX,\,Y)
$$
One of the most important properties of the distance function is that it decreases when the two values get closer to each other. Notice that $ax - y$ is not a valid distance, as it doesn't have this property (think of what happens when $ax$ is bigger vs smaller than $y$). Valid cost function could be something like a sum of squared errors $\sum_i (aX_i - Y_i)^2$, or sum of absolute errors $\sum_i |aX_i - Y_i|$, etc.
Squared error is the most popular one, and the problem described above under this error is just linear regression. In the univariate case, it doesn't even need any complicated maths to solve. For other distance functions, you will need an optimization algorithm, many of which are commonly implemented in scientific software (e.g. R's optimize or optim functions). Your code uses brute-force search which is the most trivial, but also an inefficient (both in terms of quality of the results and speed) algorithm. "Which algorithm" is problem specific. For trivial problems like the one described above (absolute error, one parameter), you can safely stick to the ones provided by R with their default settings.
