Write a program to calculate a random walk in one dimension.

RW <- function(n){
  walk <- cumsum(sample(c(-1,1), n, TRUE))
  zero <- 0
  ans <- c()
  for (i in walk){
    if (i == 0){
      ans <- c(ans, zero) 
      zero <- 0
    } else{
      zero <- zero +1
    }
  }
  num <- length(ans)
  return(list(ans, num))
}
RW(100)
## [[1]]
##  [1] 1 1 1 1 3 1 3 1 1 1 1 9 1 1
## 
## [[2]]
## [1] 14

The Walker will always return to his starting place given a that the movement set contains a positive and negative number (e.g., \((-1,1)\) and that the probability of movement in any direction \((P)\) is not asympopically 1 or 0.

b)

Write a program to simulate a random walk of two people meeting in 2D. This can be simplified to one walker returning to (0,0).

http://www.ggplot2-exts.org/gganimate.html

#devtools::install_github("dgrtwo/gganimate")
library(ggplot2)
library(gganimate)
RW2d <- function(n){
  walkM <- matrix(0, ncol = 2, nrow = n)
  for (i in 2:n){
    dimension <- sample(c(1, 2), 1, TRUE)
    direction <- sample(c(-1, 1), 1, TRUE)
    walkM[i, dimension] <- direction + walkM[i-1, dimension]
    walkM[i, -dimension] = walkM[i-1, -dimension]
  }
  zero <- 0
  ans <- c()
  for (i in 1:n){
    if (walkM[i, 1] == 0 & walkM[i, 2] == 0){
      ans <- c(ans, zero) 
      zero <- 0
    } else{
      zero <- zero + 1
    }
  return(walkM)
  }
}
x <- RW2d(100)

countGaps <- function(x){
  ans <- c()
zero <- 0
for (i in 1:nrow(x)){
  if (x[i, 1] == 0 & x[i,2] == 0){
    ans <- c(ans, zero) 
    zero <- 0
    } else{
      zero <- zero + 1
    }}
return(list(ans, length(ans)))
}
countGaps(x)
## [[1]]
## [1] 0
## 
## [[2]]
## [1] 1

https://community.rstudio.com/t/tweenr-gganimate-with-line-plot/4027/5

library(tidyverse)
## Warning: replacing previous import by 'tidyr::%>%' when loading 'broom'
## Warning: replacing previous import by 'tidyr::gather' when loading 'broom'
## Warning: replacing previous import by 'tidyr::spread' when loading 'broom'
## ── Attaching packages ───────────────────────────────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
## ✔ tibble  1.4.2     ✔ purrr   0.2.4
## ✔ tidyr   0.7.2     ✔ dplyr   0.7.4
## ✔ readr   1.1.1     ✔ stringr 1.2.0
## ✔ tibble  1.4.2     ✔ forcats 0.2.0
## ── Conflicts ──────────────────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
df <- data.frame(x)
dat_ani <- map(seq(nrow(df)), ~df[c(seq(.x), rep(.x, nrow(df) - .x)), ]) %>% 
    tweenr::tween_states(5, 2, 'cubic-in-out', 10) %>% 
    ggplot(aes(X1, X2, frame = .frame)) + 
    geom_path() + 
    geom_point()

animation::ani.options(interval = 0.000000001)    # speed it up
gganimate::gganimate(dat_ani, title_frame = FALSE)