AJI
AJI

Reputation: 51

How to calculate a slope of lines by factor

I do not know how to get a slope of a line by factor. Below are my data;

ID  x   y
1   2.43136376  0.38584994
1   2.68124124  0.42833589
1   2.35218252  0.37147102
1   2.51851394  0.40114436
1   2.38021124  0.3766155
1   2.62324929  0.41883956
1   2.97543181  0.47355
1   1.60205999  0.20467877
1   2.97772361  0.47388438
4   2.79934055  0.44705574
4   2.8920946   0.46121249
4   2.76715587  0.44203362
4   2.88366144  0.45994427
4   2.65321251  0.42377204
4   2.07918125  0.31789235
4   2.88081359  0.45951516
4   2.07918125  0.31789235
4   2.64345268  0.42217154
4   2.43136376  0.38584994
4   2.51188336  0.39999947
4   2.81954394  0.45017887
4   2.11394335  0.32509335

The slope for ID1 and ID4 are 5.10 and 5.65, respectively.

Do you all know how to calculate and extract a slope of a line by factor efficiently?

Upvotes: 1

Views: 210

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101568

Maybe you can use lm

slopes <- sapply(split(df,df$ID), function(v) lm(x~y,v)$coefficients["y"])

such that

> slopes
     1.y      4.y 
5.099948 5.650415 

Upvotes: 0

Related Questions