Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
cov cor r-squared in R
## create example data
x <- 1:20
y <- 35 + 5.5*x
## add some random noise to y
set.seed(99)
y <- y + rnorm(n = 20, mean = 2, sd = 5)
## create a data frame of xy
df <- data.frame(distance = x, fare = y)
summary(df)
## create a scatter plot
plot(x, y, pch=16, type="b",
main = "Taxi Fare Prediction",
xlab = "Distance (km)", ylab = "Fare (THB)")
abline(coef(lm(fare ~ distance, data = df)), col = "red", lty = "dashed")
## export csv file
write.csv(df, "taxi.csv", row.names = FALSE)
## covariance
cov(x,y)
sum((x - mean(x)) * (y-mean(y))) * 1/(length(x)-1)
## correlation
cor(x,y)
cov(x,y) / (sd(x) * sd(y))
## r-squared
cor(x,y) ** 2
summary(lm(y ~ x, data = df))$r.squared
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.