norm <- rnorm(100, mean = 0, sd = 1)
A <- c("a", "a", "b", "b")
B <- c(5, 10, 15, 20)
dataframe <- data.frame(A, B)
print(dataframe)
##   A  B
## 1 a  5
## 2 a 10
## 3 b 15
## 4 b 20
##   A  B
## 1 a  5
## 2 a 10
## 3 b 15
## 4 b 20
A <- c("a", "a", "b", "b")
B <- c(5, 10, 15, 20)
dataframe <- data.frame(A, B)
print(dataframe)
##   A  B
## 1 a  5
## 2 a 10
## 3 b 15
## 4 b 20
boxplot(B~A,data=dataframe)

dataframe
##   A  B
## 1 a  5
## 2 a 10
## 3 b 15
## 4 b 20
library(knitr)
## Warning: package 'knitr' was built under R version 4.2.3
kable(dataframe, digits = 2)
A B
a 5
a 10
b 15
b 20
?kable
## starting httpd help server ... done
v <- vector()
v[1:10] <- runif(10) # populate the vector 'v' with 10 random numbers between 0 and 1
# what is runif? how do you know? how do you find out?
str(v)
##  num [1:10] 0.469 0.35 0.378 0.181 0.974 ...
v <- vector()
v[1:10] <- runif(5)
str(v)
##  num [1:10] 0.2309 0.9766 0.2698 0.0716 0.7836 ...
# Vector
v <- vector()
v[1:10] <- runif(5)
str(v)
##  num [1:10] 0.48 0.474 0.754 0.604 0.249 ...
typeof(v)
## [1] "double"
mode(v)
## [1] "numeric"
is.numeric(v)
## [1] TRUE
is.integer(v)
## [1] FALSE
A <- c("a", "a", "b", "b")
B <- c(5, 10, 15, 20)
dataframe <- data.frame(A, B)
print(dataframe)
##   A  B
## 1 a  5
## 2 a 10
## 3 b 15
## 4 b 20
boxplot(B~A,data=dataframe)

# Making a matrix

m <- matrix(data=NA, nrow=4, ncol=5)
str(m) # get the structure of the variable
##  logi [1:4, 1:5] NA NA NA NA NA NA ...
# make a list
l <- list('vec' = v, 'mat' = m)
str(l)
## List of 2
##  $ vec: num [1:10] 0.48 0.474 0.754 0.604 0.249 ...
##  $ mat: logi [1:4, 1:5] NA NA NA NA NA NA ...
# convert the matrix to a data.frame
df <- as.data.frame(m)

# or make a data frame de-novo
a <- runif(5)
b <- sample(letters[seq(from = 1, to = 5)]) # figure out what I did here.

df <- data.frame(a, b, row.names = c('r1', 'r2', 'r3', 'r4', 'r5'))

str(df)
## 'data.frame':    5 obs. of  2 variables:
##  $ a: num  0.881 0.576 0.904 0.589 0.907
##  $ b: chr  "b" "e" "c" "a" ...
# square brackets allow us to access subsets of the matrix or dataframe
# m[row,column]
# df[row,column]
m[1,2] <- 4 # add the number 4 to row 1, column 2 of m

m[2,3] <- "word" # add the text string word to matrix row 2, col 3
m
##      [,1] [,2] [,3]   [,4] [,5]
## [1,] NA   "4"  NA     NA   NA  
## [2,] NA   NA   "word" NA   NA  
## [3,] NA   NA   NA     NA   NA  
## [4,] NA   NA   NA     NA   NA
# note that the number is now a character and the string is still a character


df[1,1] <- 4
df[2,2] <- "word"
df
##            a    b
## r1 4.0000000    b
## r2 0.5761156 word
## r3 0.9036934    c
## r4 0.5892854    a
## r5 0.9069879    d
# note that the number remains a number since data frames can have
# different data types

# you can make your own functions
add.matrix <- function(matrix1, matrix2){
  x <- (matrix1+matrix2)
  return(x/2)
}
data(anscombe)  # load the anscombe data
str(anscombe) # get the structure
## 'data.frame':    11 obs. of  8 variables:
##  $ x1: num  10 8 13 9 11 14 6 4 12 7 ...
##  $ x2: num  10 8 13 9 11 14 6 4 12 7 ...
##  $ x3: num  10 8 13 9 11 14 6 4 12 7 ...
##  $ x4: num  8 8 8 8 8 8 8 19 8 8 ...
##  $ y1: num  8.04 6.95 7.58 8.81 8.33 ...
##  $ y2: num  9.14 8.14 8.74 8.77 9.26 8.1 6.13 3.1 9.13 7.26 ...
##  $ y3: num  7.46 6.77 12.74 7.11 7.81 ...
##  $ y4: num  6.58 5.76 7.71 8.84 8.47 7.04 5.25 12.5 5.56 7.91 ...
typeof(anscombe)
## [1] "list"
apply(anscombe, 2, mean)
##       x1       x2       x3       x4       y1       y2       y3       y4 
## 9.000000 9.000000 9.000000 9.000000 7.500909 7.500909 7.500000 7.500909
apply(anscombe, 2, sd)
##       x1       x2       x3       x4       y1       y2       y3       y4 
## 3.316625 3.316625 3.316625 3.316625 2.031568 2.031657 2.030424 2.030579
cor(anscombe[,1], anscombe[,5])
## [1] 0.8164205
cor(anscombe[,2], anscombe[,6])
## [1] 0.8162365
cor(anscombe[,3], anscombe[,7])
## [1] 0.8162867
cor(anscombe[,4], anscombe[,8])
## [1] 0.8165214
jnk <- vector("list")
for(i in 1:4){
  jnk$pearson[i] <- round(cor(anscombe[,i], anscombe[,i+4], method="pearson"),3)
  jnk$spearman[i] <- round(cor(anscombe[,i], anscombe[,i+4], method="spearman"),3)
  jnk$kendall[i] <- round(cor(anscombe[,i], anscombe[,i+4], method="kendall"),3)
}
jnk
## $pearson
## [1] 0.816 0.816 0.816 0.817
## 
## $spearman
## [1] 0.818 0.691 0.991 0.500
## 
## $kendall
## [1] 0.636 0.564 0.964 0.426
par(mfrow=c(2,2)) # set the plotting parameters
# why not use a for loop here?

plot(anscombe[,5]~anscombe[,1], xlim=c(0,15), ylim=c(0,15), main=c(jnk$pearson[1],  jnk$spearman[1], jnk$kendall[1]))
abline(lm(anscombe[,5]~anscombe[,1]))
plot(anscombe[,6]~anscombe[,2], col="blue", main=c(jnk$pearson[2],  jnk$spearman[2], jnk$kendall[2]))
abline(lm(anscombe[,6]~anscombe[,2]), col="blue")
plot(anscombe[,7]~anscombe[,3], col="orange",main=c(jnk$pearson[3],  jnk$spearman[3], jnk$kendall[3]))
abline(lm(anscombe[,7]~anscombe[,3]), col="orange")
plot(anscombe[,8]~anscombe[,4], col="magenta",main=c(jnk$pearson[4],  jnk$spearman[4], jnk$kendall[4]))
abline(lm(anscombe[,8]~anscombe[,4]), col="magenta")

library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.2.3
library(data.table)
## Warning: package 'data.table' was built under R version 4.2.3
library(tibble)
## Warning: package 'tibble' was built under R version 4.2.3
# melt() reformats data into a tidy format
#     measure.vars find the variables by name to melt
#     value.name name the columns for the output
#     variable.name name for data column groups
ansc.tidy <- melt(as.data.table(anscombe), 
     measure.vars = patterns(c("x", "y")), 
     value.name=c('a', 'b'), 
     variable.name = "gp")
     
ansc.tidy <- as_tibble(ansc.tidy)

# ggplot() defines plots using a grammar of graphics
#   consisting of data and co-ordinate system
#   then there are add-ons and transformations

ggplot(ansc.tidy, mapping = aes(x=a, y=b, colour=gp)) + # aes defined once
  geom_point(alpha=0.5) + geom_smooth(method='lm', formula=y~x) + facet_wrap(~gp)

p-values

z <- function(size){
  d1 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  d2 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  dt <- t.test(d1,d2) # simple Welch's t test
  diff <- as.numeric(dt$estimate[1]) - as.numeric(dt$estimate[2])
  sd.diff <- sd(d1) - sd(d2)
  return(c(dt$p.value, diff, sd.diff))
}

# this is tricky, another way to do a for loop that is more
# efficient using l(s)apply

n.random = 10
# apply over the vector of values output by rep() function z
t.out <- sapply(rep(5,n.random), z)

# what happens when we change sample size?
# investigate t.out 

#####
# as a for loop
n.samples = 10 # number of p values calculated
size = 3 # sample size

t.for <- matrix(data=NA, ncol=n.samples, nrow=2)
for( i in 1:n.samples){
  size = 10
  d1 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  d2 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  dt <- t.test(d1,d2) # simple Welch's t test
  diff <- as.numeric(dt$estimate[1]) - as.numeric(dt$estimate[2])
  t.for[1,i] <- dt$p.value
  t.for[2,i] <- diff
}

# p-values captured in row 1
# difference between random vectors captured in row 2
hist(t.out[1,], breaks=99)
abline(v=0.05, lty=2, col='cyan')

plot(t.out[2,], -1*log10(t.out[1,]),  pch=19, col=rgb(0,0,0,0.1),
  xlab='difference', ylab='-log10(p)' )
abline(h=-1*log10(0.05), lty=2, col='cyan')

set.seed=100
  size=10000
  d1 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  d2 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  d0.5 <- rnorm(size, 0.5, 1) # random normal data with mean=0 and sd=1
  d1.0 <- rnorm(size, 1, 1) # random normal data with mean=0 and sd=1
  d2.0 <- rnorm(size, 2, 1) # random normal data with mean=0 and sd=1

plot(density(d1), col='black', xlim=c(-4,6), ylim=c(0,0.4), lwd=3) 
points(density(d2), col='blue', lty=2, type='l', lwd=3) 
points(density(d0.5), col='red', lty=2, type='l', lwd=3) 
points(density(d1.0), col='cyan', lty=2, type='l',lwd=3) 
points(density(d2.0), col='orange', lty=2, type='l',lwd=3) 

legend(4,0.4, legend=c('norm', 'e=0', 'e=0.5', 'e=1', 'e=2'), pch=19, col=c('black','blue','red','cyan','orange'))

# p-values captured in row 1
# difference between random vectors captured in row 2
hist(p.adjust(t.out[1,]), breaks=99)
abline(v=0.05, lty=2, col='cyan')

plot(t.out[2,], -1*log10(p.adjust(t.out[1,])),  pch=19, col=rgb(0,0,0,0.1),
  xlab='difference', ylab='-log10(p)' )
abline(h=-1*log10(0.05), lty=2, col='cyan')

# I made my own function.
# takes size of dataset and does a t test on two random datasets
# drawn from the same distribution. 
z <- function(size){
  d1 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  d2 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  dt <- t.test(d1,d2) # simple Welch's t test
  # get the mean of d1 and d2
  diff <- as.numeric(dt$estimate[1]) - as.numeric(dt$estimate[2])
  sd.diff <- sd(d1) - sd(d2)
  return(c(dt$p.value, diff, sd.diff))
}

# this is tricky, another way to do a for loop that is more
# efficient using l(s)apply

n.random = 10
# apply over the vector of values output by rep() function z
t.out <- sapply(rep(100,10000), z)

# what happens when we change sample size?
# investigate t.out 

#####
# as a for loop
n.samples = 10 # number of p values calculated

t.for <- matrix(data=NA, ncol=n.samples, nrow=2)
for( i in 1:n.samples){
  size = 5
  d1 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  d2 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  dt <- t.test(d1,d2) # simple Welch's t test
  diff <- as.numeric(dt$estimate[1]) - as.numeric(dt$estimate[2])
  t.for[1,i] <- dt$p.value
  t.for[2,i] <- diff
}

# p-values captured in row 1
# difference between random vectors captured in row 2
hist(t.out[1,], breaks=99)
abline(v=0.05, lty=2, col='cyan')

plot(t.out[2,], -1*log10(t.out[1,]),  pch=19, col=rgb(0,0,0,0.1),
  xlab='difference', ylab='-log10(p)' )
abline(h=-1*log10(0.05), lty=2, col='cyan')

set.seed=100
  size=10000
  d1 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  d2 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  d0.5 <- rnorm(size, 0.5, 1) # random normal data with mean=0 and sd=1
  d1.0 <- rnorm(size, 1, 1) # random normal data with mean=0 and sd=1
  d2.0 <- rnorm(size, 2, 1) # random normal data with mean=0 and sd=1

plot(density(d1), col='black', xlim=c(-4,6), ylim=c(0,0.4), lwd=3) 
points(density(d2), col='blue', lty=2, type='l', lwd=3) 
points(density(d0.5), col='red', lty=2, type='l', lwd=3) 
points(density(d1.0), col='cyan', lty=2, type='l',lwd=3) 
points(density(d2.0), col='orange', lty=2, type='l',lwd=3) 

legend(4,0.4, legend=c('norm', 'e=0', 'e=0.5', 'e=1', 'e=2'), pch=19, col=c('black','blue','red','cyan','orange'))

z.eff <- function(size, eff){
  d1 <- rnorm(size, 0, 1) # random normal data with mean=0 and sd=1
  d2 <- rnorm(size, 0 + eff, 1) # random normal data with mean=eff and sd=1
  dt <- t.test(d1,d2)
  diff <- as.numeric(dt$estimate[1]) - as.numeric(dt$estimate[2])
  return(c(dt$p.value, diff))
}

# alter the sample size and the effect and diff in means
# explanation of sapply
# this is effectively a for loop 
# sapply(X, function, params)
# so the input is a vector of 10 repeated 10k times
# the function is z.eff
# the parameter to z.eff is 1 
t.out2 <- sapply(rep(10,10000), z.eff, 1)
plot(t.out2[1,], t.out2[2,], log='x', xlab='group 2', ylab='group 1')

#abline(v=0.05)

length(which(t.out2[1,] < 0.05))
## [1] 5452
# p-values captured in row 1
# difference between random vectors captured in row 2
hist(t.out2[1,])

hist(p.adjust(t.out2[1,]), breaks=19)
abline(v=0.05, lty=2, col='cyan')

plot(t.out2[2,], -1*log10(p.adjust(t.out[1,])),  pch=19, col=rgb(0,0,0,0.1),
  xlab='difference', ylab='-log10(p)' )
abline(h=-1*log10(0.05), lty=2, col='cyan')

conditional code

# set a collector variable, matrix of results
# matrix, column 1 will be red and blue in both A and B (even urns)
#         column 2 will be 2 red and one blue in A, and one blue in B (odd urns)
n.tests = 100

# This is a function so we can alter the number of tests easily
conditional_balls <- function(n.tests=10){
  # column 1 is the even urn results, column 2 holds the odd urn results
  out.data <- matrix(data=NA, nrow=n.tests, ncol=2)
  # make a for loop to do the even testing
  for(i in 1:n.tests){
    A.even <- c(1,0) # one blue (1), one red (0)
    B.even <- c(0,1)
    A.odd <- c(1)
    B.odd <- c(0,0,1)
    # we need a variable of the bin names
    bin =c("A", "B")
    bin.choose <- sample(bin, size=1) # works chooses a bin at random
    # put the ball choice into row i column 1 of out.data
    if(bin.choose == "A") { 
      out.data[i,1] <- sample(A.even, size=1)
      out.data[i,2] <- sample(A.odd, size=1)
     }
    else if(bin.choose == "B"){
      out.data[i,1] <- sample(B.even, size=1)
      out.data[i,2] <- sample(B.odd, size=1)
      }
    else{stop("check your logic")}
  }
return(out.data)
}

jnk <- conditional_balls(n.tests=1000)
# count the number of blue balls
colSums(jnk)/1000 # return the proportion of blue balls in the even and odd case
## [1] 0.536 0.676
# likelihood of choosing R given 1R 1B in each urn

# urn 1 contains a red (1) and blue (0) ball
u1 <- c(1,0)
u2 <- c(1,0)

# P(R|U1) = 1/2
# P(R|U2) = 1/2

# P(R) = P(R|U1) * P(U1) + P(R|U2) * P(U2)
# = 1/2 * 1/2 + 1/2 * 1/2  = 1/2 = 0.5

# urn 1 has 1 red, and urn 2 has 1 red two blue
u1 <- c(1)
u2 <- c(1,0,0)

# P(R|U1) = 1
# PR(R|U2) = 1/3

# P(U1|U1,U2) = 1/2
# P(R) = 1 * 1/2 + 1/3 * 1/2 = 3/6 + 1/6 = 4/6 = 2/3

# from each urn choose a ball at random and tabulate it
# alternatively, choose many balls with replacement and tabulate the number of events

# we need a parameter for the number of events
nchoose = 100

# we need a summary matrix for urn 1, urn 2
mat.out <- matrix(data=NA, nrow=nchoose, ncol=2)


mat.out[,1] <- sample(u1, nchoose, replace=TRUE)
mat.out[,2] <- sample(u2, nchoose, replace=TRUE)

colSums(mat.out)
## [1] 100  31
sens = 0.9 # test sensitivity (controls TP)
spec = 1-0.8 # test specificity (controls FP) #note this is 1-specificity
pop = 0.01 # background frequency

clin.dec <- function(sens=0.9, spec=0.2, pop.f=0.01){
  # will use a standard population size of 100000
  pop.size = 100000
  pop.pre.pos <- pop.size * pop.f
  pop.pre.neg <- pop.size - pop.pre.pos #  alternatively 100000 * (1-pop.f)
  
  post.test.TP <- pop.pre.pos * sens
  post.test.FN <- pop.pre.pos * (1-sens)
  
  post.test.FP <- pop.pre.neg * spec
  post.test.TN <- pop.pre.neg * (1-spec)
  
  post.test.pos <- post.test.TP / (post.test.TP + post.test.FP)
  post.test.neg <- post.test.TN / (post.test.TN + post.test.FN)
  
  return(c(post.test.pos,post.test.neg))
}

# sensitivity = 0.7
# specificity = 0.87
# pop.f = .475%
clin.dec(sens=0.7, spec=(1-0.87), pop.f=0.00475)
## [1] 0.0250551 0.9983570