I have a line and points placed on this line. I am looking for a solution that allows to determine the distance of each point from the beginning of the line using R (preferably sf packet).
This problem and its very good solution for QGIS is described at Points layer distance from the start of line layer in QGIS I use this solutions and works well. However, I cannot implement it in R. I cannot use the qgisprocess package for this purpose https://github.com/paleolimbot/qgisprocess This package has an algorithm for generating geometry using QGIS expression ("native:geometrybyexpression"), but the above-mentioned the QGIS expression does not generate new geometry, it only updates the attribute table.
I have added the source code below with an example line and points for calculating the distance from the beginning of the line.
library(sf)
#> Linking to GEOS 3.9.1, GDAL 3.4.3, PROJ 7.2.1; sf_use_s2() is TRUE
linestring_matrix <- rbind(c(0, 0), c(100, 0), c(200, 100), c(400, 200), c(500, 0))
linia <- st_sfc(st_linestring(linestring_matrix))
punkty <- st_sfc(st_point(c(50,0)), st_point(c(150,50)), st_point(c(175,75)),
st_point(c(250,125)), st_point(c(350,175)), st_point( c(475,50)))
plot(linia)
plot(punkty, add=TRUE)

Created on 2022-08-09 by the reprex package (v2.0.1)
I added the expected result in the form of labels at the points (generated in QGIS):


st_castandst_sampledoes not take into account the trailing, non-integer part of line (eg with a line length of 5.9, each segment will be 1.18 units, which is a bug). There is a QGISpointsalonglinesalgorithm that can be used in R, which marks points along the line from the beginning of the line at a defined distance. Corrected code in the answer below (cannot be pasted in the comment). – wacekk Aug 10 '22 at 13:06