Last active
September 3, 2019 01:12
-
-
Save toyeiei/f4bb3a124cf5d95466513fe1337f2891 to your computer and use it in GitHub Desktop.
cov cor r-squared in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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