# Generate some random data
set.seed(123)
x <- rnorm(100)
summary(x)
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -2.30917 -0.49385  0.06176  0.09041  0.69182  2.18733

##Plot histogram

## Plot

hist(x, main = "Histogram of Random Data", xlab = "Value")

## Loading and Exploring Data

# Load a sample dataset
data(iris)

# View the first few rows of the dataset
head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa

Data visualization

# Scatter plot of iris dataset
plot(iris$Sepal.Length, iris$Sepal.Width, 
     main = "Sepal Length vs. Sepal Width",
     xlab = "Sepal Length", ylab = "Sepal Width", 
     col = iris$Species)
legend("topright", legend = levels(iris$Species), col = 1:3, pch = 1)

## Linear Regression

# Fit a linear regression model
lm_model <- lm(Petal.Width ~ Petal.Length, data = iris)

# Summary of the model
summary(lm_model)
## 
## Call:
## lm(formula = Petal.Width ~ Petal.Length, data = iris)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.56515 -0.12358 -0.01898  0.13288  0.64272 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  -0.363076   0.039762  -9.131  4.7e-16 ***
## Petal.Length  0.415755   0.009582  43.387  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.2065 on 148 degrees of freedom
## Multiple R-squared:  0.9271, Adjusted R-squared:  0.9266 
## F-statistic:  1882 on 1 and 148 DF,  p-value: < 2.2e-16
# Plot the regression line
plot(iris$Petal.Length, iris$Petal.Width, 
     main = "Petal Width vs. Petal Length with Regression Line",
     xlab = "Petal Length", ylab = "Petal Width")
abline(lm_model, col = "red")

## Interactive Plot

# Load the plotly library
library(plotly)
## Warning: 程辑包'plotly'是用R版本4.3.3 来建造的
## 载入需要的程辑包:ggplot2
## 
## 载入程辑包:'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
# Scatter plot using plotly
plot_ly(iris, x = ~Petal.Length, y = ~Petal.Width, color = ~Species,
        type = 'scatter', mode = 'markers', 
        marker = list(size = 10)) %>%
  layout(title = "Interactive Scatter Plot: Petal Width vs. Petal Length",
         xaxis = list(title = "Petal Length"),
         yaxis = list(title = "Petal Width"))