library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggthemes)
library(ggrepel)
library(wikipediatrend)
## 
##   [wikipediatrend]
##     
##   Note:
##     
##     - Data before 2016-01-01 
##       * is provided by petermeissner.de and
##       * was prepared in a project commissioned by the Hertie School of Governance (Prof. Dr. Simon Munzert)
##       * and supported by the Daimler and Benz Foundation.
##     
##     - Data from 2016-01-01 onwards 
##       * is provided by the Wikipedia Foundation
##       * via its pageviews package and API.
## 
# time series toolkits
library(xts)
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## 
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## 
## ######################### Warning from 'xts' package ##########################
## #                                                                             #
## # The dplyr lag() function breaks how base R's lag() function is supposed to  #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or       #
## # source() into this session won't work correctly.                            #
## #                                                                             #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop           #
## # dplyr from breaking base R's lag() function.                                #
## #                                                                             #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## ###############################################################################
## 
## Attaching package: 'xts'
## 
## The following objects are masked from 'package:dplyr':
## 
##     first, last
library(tsibble)
## 
## Attaching package: 'tsibble'
## 
## The following object is masked from 'package:zoo':
## 
##     index
## 
## The following object is masked from 'package:lubridate':
## 
##     interval
## 
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, union

Part 1:

Select a column of your data that encodes time (e.g., “date”, “timestamp”, “year”, etc.). Convert this into a Date in R. Note, you may need to use some combination of as.Date, or to_datetime. And, you may even need to paste year, month, day, hour, etc. together using paste (even if you need to make up a month, like "__/01/01").

I selected two data sets one from Wikipedia, containing social media data and one containing housing price data from R data sets. Since my student data set do not include a specific column that represents time information.

Part 2:

If you do not have a time-based column of data: find a Wikipedia page that is related to your dataset. Then, extract a time series of page views for that page using the wikipedia page views website Links to an external site. or the R package used in this week’s lab.

If you choose this option, find ways to tie your results from the below analysis into what you’re seeing with your own data!

# Load the AmesHousing dataset
ames <- AmesHousing::make_ames()

# Rename columns to lowercase
ames <- ames |> dplyr::rename_all(tolower)

First, ames dataset:

# Assuming 'ames' is your dataset
ames_timeseries <- ames %>%
  select(sale_price, neighborhood, overall_cond, year_built, overall_qual,
         second_flr_sf, first_flr_sf, bedroom_abvgr, mo_sold) %>%
  distinct()

# Display the first few rows of the ames_timeseries dataset
head(ames_timeseries)
## # A tibble: 6 × 9
##   sale_price neighborhood overall_cond  year_built overall_qual  second_flr_sf
##        <int> <fct>        <fct>              <int> <fct>                 <int>
## 1     215000 North_Ames   Average             1960 Above_Average             0
## 2     105000 North_Ames   Above_Average       1961 Average                   0
## 3     172000 North_Ames   Above_Average       1958 Above_Average             0
## 4     244000 North_Ames   Average             1968 Good                      0
## 5     189900 Gilbert      Average             1997 Average                 701
## 6     195500 Gilbert      Above_Average       1998 Above_Average           678
## # ℹ 3 more variables: first_flr_sf <int>, bedroom_abvgr <int>, mo_sold <int>

Second Date Frame From Wikipedia:

socialmedia_data <- read.csv("/Users/shemaaeltayeb/Desktop/STATISTIC IN R /pageviews-20150701-20231031.csv")
print(socialmedia_data)
##        Date Social.media
## 1   2015-07       116985
## 2   2015-08       125961
## 3   2015-09       140022
## 4   2015-10       161001
## 5   2015-11       153429
## 6   2015-12       127513
## 7   2016-01       142148
## 8   2016-02       167701
## 9   2016-03       166133
## 10  2016-04       137823
## 11  2016-05       136331
## 12  2016-06       117872
## 13  2016-07       116100
## 14  2016-08       128835
## 15  2016-09       147754
## 16  2016-10       172278
## 17  2016-11       170337
## 18  2016-12       127935
## 19  2017-01       155260
## 20  2017-02       154187
## 21  2017-03       173053
## 22  2017-04       152094
## 23  2017-05       148345
## 24  2017-06       133647
## 25  2017-07       142928
## 26  2017-08       143284
## 27  2017-09       151193
## 28  2017-10       165853
## 29  2017-11       180479
## 30  2017-12       142086
## 31  2018-01       163977
## 32  2018-02       159211
## 33  2018-03       163543
## 34  2018-04       148190
## 35  2018-05       159068
## 36  2018-06       149584
## 37  2018-07       166341
## 38  2018-08       159306
## 39  2018-09       184024
## 40  2018-10       210148
## 41  2018-11       168101
## 42  2018-12       130147
## 43  2019-01       158034
## 44  2019-02       163433
## 45  2019-03       171327
## 46  2019-04       155493
## 47  2019-05       142700
## 48  2019-06       129232
## 49  2019-07       138964
## 50  2019-08       130657
## 51  2019-09       158214
## 52  2019-10       162224
## 53  2019-11       160399
## 54  2019-12       133178
## 55  2020-01       153794
## 56  2020-02       159804
## 57  2020-03       135413
## 58  2020-04       113865
## 59  2020-05       101891
## 60  2020-06        90163
## 61  2020-07        84878
## 62  2020-08        94635
## 63  2020-09       107896
## 64  2020-10       124390
## 65  2020-11       121499
## 66  2020-12       108224
## 67  2021-01       132778
## 68  2021-02       143959
## 69  2021-03       150886
## 70  2021-04       123981
## 71  2021-05       124340
## 72  2021-06       119561
## 73  2021-07        99238
## 74  2021-08        99032
## 75  2021-09       107992
## 76  2021-10       126976
## 77  2021-11       123886
## 78  2021-12       117630
## 79  2022-01       131798
## 80  2022-02       131593
## 81  2022-03       129445
## 82  2022-04       117487
## 83  2022-05       124792
## 84  2022-06       108865
## 85  2022-07       106072
## 86  2022-08       103508
## 87  2022-09       110366
## 88  2022-10       130077
## 89  2022-11       149126
## 90  2022-12       118399
## 91  2023-01       135318
## 92  2023-02       140024
## 93  2023-03       162796
## 94  2023-04       124123
## 95  2023-05       151562
## 96  2023-06       126208
## 97  2023-07       135709
## 98  2023-08       140845
## 99  2023-09       126946
## 100 2023-10       142300

Remove duplicate rows in social media dataset:

# Remove duplicate rows in social media data set:
socialmedia_data<- socialmedia_data %>%
  distinct()

# Check the structure of the dataset after removing duplicates
sum(is.na(socialmedia_data))
## [1] 0
anyDuplicated(socialmedia_data)
## [1] 0
str(socialmedia_data)
## 'data.frame':    100 obs. of  2 variables:
##  $ Date        : chr  "2015-07" "2015-08" "2015-09" "2015-10" ...
##  $ Social.media: int  116985 125961 140022 161001 153429 127513 142148 167701 166133 137823 ...

learn more about the social media dataset:

unique(socialmedia_data$Date)
##   [1] "2015-07" "2015-08" "2015-09" "2015-10" "2015-11" "2015-12" "2016-01"
##   [8] "2016-02" "2016-03" "2016-04" "2016-05" "2016-06" "2016-07" "2016-08"
##  [15] "2016-09" "2016-10" "2016-11" "2016-12" "2017-01" "2017-02" "2017-03"
##  [22] "2017-04" "2017-05" "2017-06" "2017-07" "2017-08" "2017-09" "2017-10"
##  [29] "2017-11" "2017-12" "2018-01" "2018-02" "2018-03" "2018-04" "2018-05"
##  [36] "2018-06" "2018-07" "2018-08" "2018-09" "2018-10" "2018-11" "2018-12"
##  [43] "2019-01" "2019-02" "2019-03" "2019-04" "2019-05" "2019-06" "2019-07"
##  [50] "2019-08" "2019-09" "2019-10" "2019-11" "2019-12" "2020-01" "2020-02"
##  [57] "2020-03" "2020-04" "2020-05" "2020-06" "2020-07" "2020-08" "2020-09"
##  [64] "2020-10" "2020-11" "2020-12" "2021-01" "2021-02" "2021-03" "2021-04"
##  [71] "2021-05" "2021-06" "2021-07" "2021-08" "2021-09" "2021-10" "2021-11"
##  [78] "2021-12" "2022-01" "2022-02" "2022-03" "2022-04" "2022-05" "2022-06"
##  [85] "2022-07" "2022-08" "2022-09" "2022-10" "2022-11" "2022-12" "2023-01"
##  [92] "2023-02" "2023-03" "2023-04" "2023-05" "2023-06" "2023-07" "2023-08"
##  [99] "2023-09" "2023-10"
sum(is.na(socialmedia_data$Date))
## [1] 0
str(socialmedia_data)
## 'data.frame':    100 obs. of  2 variables:
##  $ Date        : chr  "2015-07" "2015-08" "2015-09" "2015-10" ...
##  $ Social.media: int  116985 125961 140022 161001 153429 127513 142148 167701 166133 137823 ...
head(socialmedia_data)
##      Date Social.media
## 1 2015-07       116985
## 2 2015-08       125961
## 3 2015-09       140022
## 4 2015-10       161001
## 5 2015-11       153429
## 6 2015-12       127513
socialmedia_data$Date <- as.Date(socialmedia_data$Date, format = "your_date_format")

Part 3:

Choose a column of data to analyze over time. This should be a “response-like” variable that is of particular interest.

“Sale_Price column”: This column represents the sale prices of houses. Analyzing this variable over time can provide insights into the changing real estate market trends, property value changes , and economic factors affecting housing prices over different periods.

Analyzing the sale prices over time can involve techniques such as calculating average sale prices per month or year, identifying trends, seasonality, or potential patterns related to economic events or market conditions.

Part 4:

Create a tsibble object of just the date and response variable. Then, plot your data over time. Consider different windows of time. What stands out immediately?

First, will Filter relevant columns and save them in ames_timeseries data frame:

# Filter relevant columns and remove duplicates
ames_timeseries <- ames |>
  select(sale_price, year_built, overall_qual,
        second_flr_sf,first_flr_sf, bedroom_abvgr,mo_sold)|>
  distinct()

# View the filtered data:
view(ames_timeseries)

Second, want to make sure the data in ames_timeseries is ready to use and check the missing values and the duplicates :

# Remove duplicate rows in ames_timeseries
ames_timeseries <- ames_timeseries %>%
  distinct()

# Check the structure of the dataset after removing duplicates

#str(ames_timeseries)
sum(is.na(ames_timeseries))
## [1] 0
anyDuplicated(ames_timeseries)
## [1] 0

Third, Create a tsibble of sale prices over years:

# Example assuming the dataset is in a CSV file
ames_timeseries_ts <- ames_timeseries 
ames_timeseries_ts <- ames_timeseries_ts %>%
  select(year_built, sale_price)
ames_timeseries_ts$year_built<- as.Date(paste0(ames_timeseries_ts$year_built, "-01-01"))
ames_timeseries_ts$year_built<- as.Date(paste0(ames_timeseries_ts$year_built,"-01-01"))
 
print(ames_timeseries_ts)
## # A tibble: 2,925 × 2
##    year_built sale_price
##    <date>          <int>
##  1 1960-01-01     215000
##  2 1961-01-01     105000
##  3 1958-01-01     172000
##  4 1968-01-01     244000
##  5 1997-01-01     189900
##  6 1998-01-01     195500
##  7 2001-01-01     213500
##  8 1992-01-01     191500
##  9 1995-01-01     236500
## 10 1999-01-01     189000
## # ℹ 2,915 more rows
view(ames_timeseries_ts)
ames_timeseries_ts %>%
  filter(year_built >= as.Date("1958-01-01") & year_built <= as.Date("2001-01-01")) %>%
  ggplot(mapping = aes(x = year_built, y = sale_price)) +
  geom_line() +
  geom_smooth(method = 'lm', color = 'blue', se = FALSE) +
  labs(title = "Sales Prices Over Time (1958-2001)") +
  theme_hc()
## `geom_smooth()` using formula = 'y ~ x'

Fourth, Convert to xts object :

# Convert to an xts object
xts_data <- xts(ames_timeseries$mo_sold, order.by = as.Date(paste0(ames_timeseries$year_built, "-01-01")))
xts_data <- setNames(xts_data, "mo_sold")
# Print the xts object
print(xts_data)
##            mo_sold
## 1872-01-01      12
## 1875-01-01       5
## 1879-01-01       2
## 1880-01-01       5
## 1880-01-01       6
## 1880-01-01       5
## 1880-01-01       5
## 1880-01-01       6
## 1882-01-01      11
## 1885-01-01       4
##        ...        
## 2009-01-01       9
## 2009-01-01       9
## 2009-01-01      10
## 2009-01-01       6
## 2009-01-01       6
## 2009-01-01       7
## 2009-01-01       7
## 2010-01-01       6
## 2010-01-01       4
## 2010-01-01       3
# Convert to an xts object
xts_data <- xts(ames_timeseries$mo_sold, order.by = as.Date(paste0(ames_timeseries$year_built, "-01-01")))

# Plot the time series:
plot(ames_timeseries$year_built, main = "months Sold ", ylab = "ames_timeseries$mo_sold")

Part 5:

Use linear regression to detect any upwards or downwards trends. Do you need to subset the data for multiple trends? How strong are these trends?

Use smoothing to detect at least one season in your data, and interpret your results. Can you illustrate the seasonality using ACF or PACF?

# Fit a linear model
linear_model <- lm(sale_price ~ as.numeric(year_built), data = ames_timeseries_ts)

# Summarize the model
summary(linear_model)
## 
## Call:
## lm(formula = sale_price ~ as.numeric(year_built), data = ames_timeseries_ts)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -147384  -41138  -14507   23065  540802 
## 
## Coefficients:
##                         Estimate Std. Error t value Pr(>|t|)    
## (Intercept)            1.788e+05  1.227e+03  145.74   <2e-16 ***
## as.numeric(year_built) 4.035e+00  1.109e-01   36.38   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 66300 on 2923 degrees of freedom
## Multiple R-squared:  0.3116, Adjusted R-squared:  0.3114 
## F-statistic:  1323 on 1 and 2923 DF,  p-value: < 2.2e-16

In summary, the model suggests that there is a statistically significant relationship between the “year_built” and “sale_price” variable.

linear regression:

# Fit a linear model
linear_model <- lm(sale_price ~ as.numeric(year_built), data = ames_timeseries_ts)

# Scatter plot with linear regression line
ggplot(ames_timeseries_ts, aes(x = year_built, y = sale_price)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, color = "blue") +
  labs(title = "Linear Regression: year_built vs. sale_price",
       x = "Year Built",
       y = "Sale Price")
## `geom_smooth()` using formula = 'y ~ x'