Title: | Beginning Computer Science with R |
---|---|
Description: | Functions and datasets to accompany the text Beginning Computer Science with R (https://homerhanumat.github.io/r-notes). |
Authors: | Homer White [aut, cre] |
Maintainer: | Homer White <[email protected]> |
License: | GPL (>=3) |
Version: | 0.1.4 |
Built: | 2025-02-12 06:02:39 UTC |
Source: | https://github.com/homerhanumat/bcscr |
Find and graph the Collatz sequence from a given initial number.
collatz(n, limit = 10000)
collatz(n, limit = 10000)
n |
the initial integer |
limit |
maximum number of members of the Collatz sequence to compute |
side effects
Homer White [email protected]
## Not run: collatz(1757) ## End(Not run)
## Not run: collatz(1757) ## End(Not run)
In this version all five judges vote independently.
courtSim(reps = 10000, seed = NULL, table = FALSE, probs = c(0.95, 0.94, 0.90, 0.90, 0.80))
courtSim(reps = 10000, seed = NULL, table = FALSE, probs = c(0.95, 0.94, 0.90, 0.90, 0.80))
reps |
number of simulations to perform |
seed |
The user may provide a seed-value for random-number generation. |
table |
Does the user want a table of the results? |
probs |
Chance for each judge to make the right decision on any given case. |
side effects
Homer White [email protected]
courtSim(seed = 3030)
courtSim(seed = 3030)
In this version the weakest judge always votes with the strongest one.
courtSim2(reps = 10000, seed = NULL, table = FALSE, probs = c(0.95, 0.94, 0.90, 0.90, 0.80))
courtSim2(reps = 10000, seed = NULL, table = FALSE, probs = c(0.95, 0.94, 0.90, 0.90, 0.80))
reps |
number of simulations to perform |
seed |
The user may provide a seed-value for random-number generation. |
table |
Does the user want a table of the results? |
probs |
Chance for each judge to make the right decision on any given case. |
side effects
Homer White [email protected]
courtSim2(seed = 3030)
courtSim2(seed = 3030)
Manipulate parameters of a chosen distribution.
distExplore(options = NULL)
distExplore(options = NULL)
options |
Options that will be passed to |
side effects
Homer White [email protected]
## distExplore()
## distExplore()
A drunken turtle starts at the origin and takes unit steps, turning through a randdom angle after each step. We are interested in the distribution of the number of close-returns to the origin, for a fixed number of steps and a fixed measure of closeness.
drunkenSim(steps = 1000, reps = 10000, close = 0.5, seed = NULL, table = FALSE)
drunkenSim(steps = 1000, reps = 10000, close = 0.5, seed = NULL, table = FALSE)
steps |
the number of steps the turtle will take |
reps |
number of simulations to perform |
close |
the distance from the origin that counts as "close" |
seed |
The user may provide a seed-value for random-number generation. |
table |
Does the user want a table of the results? |
side effects
Homer White [email protected]
drunkenSim(seed = 3030)
drunkenSim(seed = 3030)
A drunken turtle starts at the origin and takes unit steps, turning through a randdom angle after each step. We graph the distance from the origin as a function of step-number.
drunkenSim2(steps = 1000, seed = NULL)
drunkenSim2(steps = 1000, seed = NULL)
steps |
the number of steps the turtle will take |
seed |
The user may provide a seed-value for random-number generation. |
side effects
Homer White [email protected]
## Not run: drunkenSim2(seed = 3030) ## End(Not run)
## Not run: drunkenSim2(seed = 3030) ## End(Not run)
A British Ford Escort was driven along a prescribed course. Each drive was done at a different speed, and the fuel efficiency was recorded for each drive.
A data frame with 15 observations on the following 2 variables.
in kilometers per hour.
fuel efficiency, measured in liters of fuel required to travel 100 kilometers.
The Basic Practice of Statistics, by Moore and McCabe.
Extracts specified portions of R help files for use in Sweave or R-markdown documents.
helpExtract(Function, section = "Usage", type = "m_code", ...)
helpExtract(Function, section = "Usage", type = "m_code", ...)
Function |
The function that you are extracting the help file from. |
section |
The section you want to extract. Defaults to |
type |
The type of character vector you want returned. Defaults to
|
... |
Other arguments passed to |
The type
argument accepts:
"m_code"
: For use
with markdown documents in instances where highlighted code is expected, for
example the "Usage" section.
"m_text"
: For use with markdown
documents in instances where regular text is expected, for example the
"Description" section.
"s_code"
: For use with Sweave documents
in instances where highlighted code is expected, for example the "Usage"
section.
"s_text"
: For use with Sweave documents in instances
where regular text is expected, for example the "Description" section.
To insert a chunk into a markdown document, use something like:
```{r, echo=FALSE, results='asis'}
cat(helpExtract(cor), sep =
"\n")
```
To insert a chunk into a Sweave document, use something like:
\Sexpr{knit_child(textConnection(helpExtract(cor, type = "s_code")),
options = list(tidy = FALSE, eval = FALSE))}
A character vector to be used in a Sweave or R-markdown document.
Reproduced here with helper functions defined from R source, so there are no ::: calls.
Ananda Mahto (https://github.com/mrdwab/SOfun)
See how density plots are built from kernels.
kdExplore(data, options = NULL)
kdExplore(data, options = NULL)
data |
A vector of numerical values from which to form the density plot. |
options |
Options that will be passed to |
side effects
Homer White [email protected]
## small custom dataset: ## myData <- c(1, 3, 5, 6, 6.2, 7, 9) ## kdExplore(myData) ## random exponential data: ## kdExplore(rexp(50, rate = 0.2))
## small custom dataset: ## myData <- c(1, 3, 5, 6, 6.2, 7, 9) ## kdExplore(myData) ## random exponential data: ## kdExplore(rexp(50, rate = 0.2))
Results of a survey of MAT 111 students at Georgetown College.
height. How tall are you, in inches?
ideal_ht. A numeric vector How tall would you LIKE to be, in inches?
sleep. How much sleep did you get last night?
fastest. What is the highest speed at which you have ever driven a car?
weight_feel. How do you feel about your weight?
love_first. Do you believe in love at first sight?
extra_life. Do you believe in extraterrestrial life?
seat. When you have a choice, where do you prefer to sit in a classroom?
GPA. What is your college GPA?
enough_Sleep. Do you think you get enough sleep?
sex. What sex are you?
diff. Your ideal height minus your actual height.
A data frame with 71 rows and 12 variables
Georgetown College, MAT 111.
Utility function to make small directed acyclic graphs, using the data.tree package. Nodes are provided with randomly-selected numerical values.
make_val_tree(min_children = 1, max_children = 4, min_depth = 3, values = 1:5, fillcolor = "palegreen", fontcolor = "black", seed = NULL)
make_val_tree(min_children = 1, max_children = 4, min_depth = 3, values = 1:5, fillcolor = "palegreen", fontcolor = "black", seed = NULL)
min_children |
Minimum number of children when node will not be a leaf. |
max_children |
Maximum number of children when node will not be a leaf. |
min_depth |
Nodes at less than this specified depth will not be leaves. |
values |
Numerical vector of possible values to associate with each node. |
fillcolor |
Fill color for nodes. |
fontcolor |
Fonot color for text showing node value and node name. |
seed |
Option to set the random seed. |
A tree object of class "Node" and "R6"
Homer White [email protected]
## Not run: tr <- make_val_tree( values = 1:10, seed = 4040, fillcolor = "lightblue" ) library(DiagrammeR) plot(tr) ## End(Not run)
## Not run: tr <- make_val_tree( values = 1:10, seed = 4040, fillcolor = "lightblue" ) library(DiagrammeR) plot(tr) ## End(Not run)
Sample data for regular expression practice.
name. Last name followed by first.
phone. Phone number with area code, in several formats.
A data frame with 50 rows and 2 variables
You pick random numbers from 0 to 1, until their sum exceeds some target number. What's the expected value of the number of numbers you have to pick?
numberNeededSim(target = 1, reps = 1000, seed = NULL, table = TRUE)
numberNeededSim(target = 1, reps = 1000, seed = NULL, table = TRUE)
target |
the target number |
reps |
number of simulations to perform |
seed |
The user may provide a seed-value for random-number generation. |
table |
Does the user want a table of the results? |
side effects
Homer White [email protected]
numberNeededSim(seed = 3030)
numberNeededSim(seed = 3030)
R6 Object for simulating a population of whales.
R6Class
object.
Object of R6Class
with methods for simulation.
dimensions
A vector of length two giving the dimensions of the ocean.
males
A list of R6 objects of class Male containing the current population of male whales.
females
A list of R6 objects of class Female containing the current population of female whales.
malePop
Current number of males in the population.
femalePop
Current number of females in the population.
starveParameter
Helps determine probability for each whale to die by starvation in the current generation.
distance()
Compute distance between two whales.
Ocean$distance(a, b)
a
one whale
b
another whale
A number
new()
Create a new Ocean object.
Ocean$new(dims = c(100, 100), males = 10, females = 10, starve = 5)
dims
numerical vector of length 2 giving the dimensions of the ocean
males
initial number of males
females
initial number of females
starve
the starvation parameter
A new 'Ocean' object.
starvationProbability()
Compute the starvation probability.
Ocean$starvationProbability(popDensity)
popDensity
population density
a number.
advance()
advance the 'Ocean' one step.
Ocean$advance()
the 'Ocean' object.
plot()
plot the 'Ocean'.
Ocean$plot()
side effect
clone()
The objects of this class are cloneable with this method.
Ocean$clone(deep = FALSE)
deep
Whether to make a deep clone.
Homer White [email protected]
## Not run: library(ggplot2) oceanSim <- function( steps = 100, males = 10, females = 10, starve = 5, animate = FALSE, seed = NULL ) { if ( !is.null(seed) ) { set.seed(seed) } ocean <- Ocean$new(dims = c(100, 100), males = males, females = females, starve = starve) population <-numeric(steps) for ( i in 1:steps ) { population[i] <- ocean$malePop + ocean$femalePop if ( animate ) ocean$plot() if ( population[i] == 0 ) break ocean$advance() if ( animate ) { ocean$plot() Sys.sleep(0.5) } } pop <- population[1:i] df <- data.frame(time = 1:length(pop), pop) ggplot(df, aes(x = time, y = pop)) + geom_line() + labs(x = "Time", y = "Whale Population") } oceanSim(seed = 5050) ## End(Not run)
## Not run: library(ggplot2) oceanSim <- function( steps = 100, males = 10, females = 10, starve = 5, animate = FALSE, seed = NULL ) { if ( !is.null(seed) ) { set.seed(seed) } ocean <- Ocean$new(dims = c(100, 100), males = males, females = females, starve = starve) population <-numeric(steps) for ( i in 1:steps ) { population[i] <- ocean$malePop + ocean$femalePop if ( animate ) ocean$plot() if ( population[i] == 0 ) break ocean$advance() if ( animate ) { ocean$plot() Sys.sleep(0.5) } } pop <- population[1:i] df <- data.frame(time = 1:length(pop), pop) ggplot(df, aes(x = time, y = pop)) + geom_line() + labs(x = "Time", y = "Whale Population") } oceanSim(seed = 5050) ## End(Not run)
Look up words in the Wizard of Oz. This is primarily a utility-function for use of webR in the book.
ozLookup(word)
ozLookup(word)
word |
a character vecotr of length 1, the word to be looked up |
side effects
Homer White [email protected]
ozLookup(word = "humbug")
ozLookup(word = "humbug")
Understand why qq-plots bend the way they do.
qqExplore(data, options = NULL)
qqExplore(data, options = NULL)
data |
A vector of numerical values from which to form the qq-plot. |
options |
Options that will be passed to |
side effects
Homer White [email protected]
## bimodal data: ## bimodal <- c(rnorm(50, 5, 1), rnorm(50, 10, 1)) ## qqExplore(bimodal) ## random exponential data: ## qqExplore(rexp(300, rate = 0.2))
## bimodal data: ## bimodal <- c(rnorm(50, 5, 1), rnorm(50, 10, 1)) ## qqExplore(bimodal) ## random exponential data: ## qqExplore(rexp(300, rate = 0.2))
This data table is modifed slightly from mosaicData::RailTrail, (see http://cran.r-project.org/web/packages/mosaicData/mosaicData.pdf). Description below is drawn from the mosaicData help file.
data(railtrail)
data(railtrail)
A data frame with 90 observations on the following variables.
hightemp daily high temperature (in degrees Fahrenheit)
lowtemp daily low temperature (in degrees Fahrenheit)
avgtemp average of daily low and daily high temperature (in degrees Fahrenheit)
season spring, summer or fall
cloudcover measure of cloud cover (in oktas)
precip measure of precipitation (in inches)
volume estimated number of trail users that day (number of breaks recorded)
weekday logical indicator of whether the day was a non-holiday weekday
dayType one of "weekday" or "weekend"
The Pioneer Valley Planning Commission (PVPC) collected data north of Chestnut Street in Florence, MA for ninety days from April 5, 2005 to November 15, 2005. Data collectors set up a laser sensor, with breaks in the laser beam recording when a rail-trail user passed the data collection station.
There is a potential for error when two users trigger the infrared beam at exactly the same time since the counter would only logs one of the crossings. The collectors left the motion detector out during the winter, but because the counter drops data when the temperature falls below 14 degrees Fahrenheit, there is no data for the cold winter months.
Pioneer Valley Planning Commission
http://www.fvgreenway.org/pdfs/Northampton-Bikepath-Volume-Counts
data(railtrail)
data(railtrail)
Break a unit length at two random points: what's the chance that the three segments produced can form a triangle?
triangleSim(reps = 10000, table = FALSE, seed = NULL)
triangleSim(reps = 10000, table = FALSE, seed = NULL)
reps |
number of simulations to perform |
table |
Does the user want a table of the results? |
seed |
The user may provide a seed-value for random-number generation. |
side effects
Homer White [email protected]
triangleSim(seed = 3030)
triangleSim(seed = 3030)
A turtle walks randomly, but bounces back from the edge of its containing field.
turtle_bounce(side = 60, step= 10)
turtle_bounce(side = 60, step= 10)
side |
side-lengths of the containing square |
step |
length of one turtle step (side-length/2 must be a multiple of step). |
side effects
Homer White [email protected]
## turtle_bounce(side = 80, step = 10)
## turtle_bounce(side = 80, step = 10)
A turtle takes steps of a fixed length, but turns at a random angle after each step.
turtle_drunk(side, step)
turtle_drunk(side, step)
side |
side-lengths of the containing square |
step |
length of one turtle step |
side effects
Homer White [email protected]
## turtle_drunk(side = 100, step = 10)
## turtle_drunk(side = 100, step = 10)
R6 Objects for modelling a whale. Female and Male inherit from whale. Use Female and Male if you want to provide custom lists of male and female whales when you instantiate an ocean.
R6Class
object.
Object of R6Class
with methods for simulation.
Boolean
sex of the resulting baby
position
A numeric vector of length 2 giving the initial position. (Make sure that it's within the dimensions of the ocean.)
age
initial age of the whale
lifespan
lifespan of the whale
range
Distance at which a female can detect an eligible male.
maturity
Age of whale at which reproduction is possible.
stepSize
Number of units the whale moves in each generation.
new()
initialize a 'Whale'.
Whale$new( position = NA, age = 3, lifespan = 40, range = 5, maturity = 10, stepSize = 5 )
position
position of whale
age
age of whale
lifespan
lifespan of whale
range
range of whale
maturity
how old whale must be in order to mate
stepSize
how far whale moves in one step
a new 'Whale' object
move()
move a whale
Whale$move(dims, r = self$stepSize)
dims
dimensions of the ocean
r
how far the whale wants to move
clone()
The objects of this class are cloneable with this method.
Whale$clone(deep = FALSE)
deep
Whether to make a deep clone.
bcscr::Whale
-> Male
sex
sex of the whale
clone()
The objects of this class are cloneable with this method.
Male$clone(deep = FALSE)
deep
Whether to make a deep clone.
bcscr::Whale
-> Female
sex
sex of the whale
timeToFertility
how long until whale can breed
infertilityPeriod
number of steps until a female can breed again after having borne a child
maleNear()
determine whether a male is near
Female$maleNear(males, dist)
males
the males in the ocean
dist
the distance-fidning function
mate()
make female whale mate
Female$mate()
clone()
The objects of this class are cloneable with this method.
Female$clone(deep = FALSE)
deep
Whether to make a deep clone.
Homer White [email protected]
## Not run: initialMales <- vector(mode = "list", length = 10) ages <- c(rep(3, 5), c(rep(10, 5))) for (i in 1:10) { initialMales[[i]] <- Male$new( position = runif(2, min = 0, max = 100), age = ages[i], lifespan = 40, range = 12, maturity = 10, stepSize = 7 ) } initialFemales <- vector(mode = "list", length = 10) for (i in 1:10) { initialFemales[[i]] <- Female$new( position = runif(2, min = 0, max = 100), age = ages[i], lifespan = 40, maturity = 10, range = 12, stepSize = 3 ) } library(ggplot2) oceanSim <- function( steps = 100, males = 10, females = 10, starve = 5, animate = FALSE, seed = NULL ) { if ( !is.null(seed) ) { set.seed(seed) } ocean <- Ocean$new(dims = c(100, 100), males = males, females = females, starve = starve) population <-numeric(steps) for ( i in 1:steps ) { population[i] <- ocean$malePop + ocean$femalePop if ( animate ) ocean$plot() if ( population[i] == 0 ) break ocean$advance() if ( animate ) { ocean$plot() Sys.sleep(0.5) } } pop <- population[1:i] df <- data.frame(time = 1:length(pop), pop) ggplot(df, aes(x = time, y = pop)) + geom_line() + labs(x = "Time", y = "Whale Population") } oceanSim(males = initialMales, females = initialFemales, seed = 5050) ## End(Not run)
## Not run: initialMales <- vector(mode = "list", length = 10) ages <- c(rep(3, 5), c(rep(10, 5))) for (i in 1:10) { initialMales[[i]] <- Male$new( position = runif(2, min = 0, max = 100), age = ages[i], lifespan = 40, range = 12, maturity = 10, stepSize = 7 ) } initialFemales <- vector(mode = "list", length = 10) for (i in 1:10) { initialFemales[[i]] <- Female$new( position = runif(2, min = 0, max = 100), age = ages[i], lifespan = 40, maturity = 10, range = 12, stepSize = 3 ) } library(ggplot2) oceanSim <- function( steps = 100, males = 10, females = 10, starve = 5, animate = FALSE, seed = NULL ) { if ( !is.null(seed) ) { set.seed(seed) } ocean <- Ocean$new(dims = c(100, 100), males = males, females = females, starve = starve) population <-numeric(steps) for ( i in 1:steps ) { population[i] <- ocean$malePop + ocean$femalePop if ( animate ) ocean$plot() if ( population[i] == 0 ) break ocean$advance() if ( animate ) { ocean$plot() Sys.sleep(0.5) } } pop <- population[1:i] df <- data.frame(time = 1:length(pop), pop) ggplot(df, aes(x = time, y = pop)) + geom_line() + labs(x = "Time", y = "Whale Population") } oceanSim(males = initialMales, females = initialFemales, seed = 5050) ## End(Not run)