[R/en] Format R code

This commit is contained in:
Crystal-RainSlide 2022-03-08 16:56:31 +08:00 committed by GitHub
parent a53abc23e2
commit 2313888888
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -91,14 +91,15 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
# 82 | 2
# make a histogram:
hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters
hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later
hist(rivers, col = "#333333", border = "white", breaks = 25)
hist(log(rivers), col = "#333333", border = "white", breaks = 25)
# play around with these parameters, you'll do more plotting later
# Here's another neat data set that comes pre-loaded. R has tons of these.
data(discoveries)
plot(discoveries, col="#333333", lwd=3, xlab="Year",
plot(discoveries, col = "#333333", lwd = 3, xlab = "Year",
main="Number of important discoveries per year")
plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year",
plot(discoveries, col = "#333333", lwd = 3, type = "h", xlab = "Year",
main="Number of important discoveries per year")
# Rather than leaving the default ordering (by year),
@ -109,7 +110,7 @@ sort(discoveries)
# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
stem(discoveries, scale=2)
stem(discoveries, scale = 2)
#
# The decimal point is at the |
#
@ -134,7 +135,7 @@ summary(discoveries)
# 0.0 2.0 3.0 3.1 4.0 12.0
# Roll a die a few times
round(runif(7, min=.5, max=6.5))
round(runif(7, min = .5, max = 6.5))
# 1 4 6 1 4 6 4
# Your numbers will differ from mine unless we set the same random.seed(31337)
@ -173,7 +174,7 @@ class(c(4L, 5L, 8L, 3L)) # "integer"
class(5) # "numeric"
# Again, everything in R is a vector;
# you can make a numeric vector with more than one element
c(3,3,3,2,2,1) # 3 3 3 2 2 1
c(3, 3, 3, 2, 2, 1) # 3 3 3 2 2 1
# You can use scientific notation too
5e4 # 50000
6.02e23 # Avogadro's number
@ -197,15 +198,15 @@ class(-Inf) # "numeric"
class(NaN) # "numeric"
# You can do arithmetic on two vectors with length greater than 1,
# so long as the larger vector's length is an integer multiple of the smaller
c(1,2,3) + c(1,2,3) # 2 4 6
c(1, 2, 3) + c(1, 2, 3) # 2 4 6
# Since a single number is a vector of length one, scalars are applied
# elementwise to vectors
(4 * c(1,2,3) - 2) / 2 # 1 3 5
(4 * c(1, 2, 3) - 2) / 2 # 1 3 5
# Except for scalars, use caution when performing arithmetic on vectors with
# different lengths. Although it can be done,
c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
# Matching lengths is better practice and easier to read
c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
c(1, 2, 3, 1, 2, 3) * c(1, 2) # 1 4 3 2 2 6
# Matching lengths is better practice and easier to read most times
c(1, 2, 3, 1, 2, 3) * c(1, 2, 1, 2, 1, 2) # 1 4 3 2 2 6
# CHARACTERS
# There's no difference between strings and characters in R
@ -215,8 +216,7 @@ class('H') # "character"
# Those were both character vectors of length 1
# Here is a longer one:
c('alef', 'bet', 'gimmel', 'dalet', 'he')
# =>
# "alef" "bet" "gimmel" "dalet" "he"
# => "alef" "bet" "gimmel" "dalet" "he"
length(c("Call","me","Ishmael")) # 3
# You can do regex operations on character vectors:
substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
@ -230,6 +230,7 @@ month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "D
# LOGICALS
# In R, a "logical" is a boolean
class(TRUE) # "logical"
class(FALSE) # "logical"
# Their behavior is normal
@ -245,8 +246,8 @@ TRUE | FALSE # TRUE
# AND
TRUE & FALSE # FALSE
# Applying | and & to vectors returns elementwise logic operations
c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
c(TRUE, FALSE, FALSE) | c(FALSE, TRUE, FALSE) # TRUE TRUE FALSE
c(TRUE, FALSE, TRUE) & c(FALSE, TRUE, TRUE) # FALSE FALSE TRUE
# You can test if x is TRUE
isTRUE(TRUE) # TRUE
# Here we get a logical vector with many elements:
@ -255,7 +256,7 @@ c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
# FACTORS
# The factor class is for categorical data
# Factors can be ordered (like childrens' grade levels) or unordered (like colors)
# Factors can be ordered (like grade levels) or unordered (like colors)
factor(c("blue", "blue", "green", NA, "blue"))
# blue blue green <NA> blue
# Levels: blue green
@ -273,13 +274,9 @@ levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
# "NULL" is a weird one; use it to "blank out" a vector
class(NULL) # NULL
parakeet = c("beak", "feathers", "wings", "eyes")
parakeet
# =>
# [1] "beak" "feathers" "wings" "eyes"
parakeet # "beak" "feathers" "wings" "eyes"
parakeet <- NULL
parakeet
# =>
# NULL
parakeet # NULL
# TYPE COERCION
# Type-coercion is when you force a value to take on a different type
@ -310,8 +307,9 @@ as.numeric("Bilbo")
# VARIABLES
# Lots of way to assign stuff:
x = 5 # this is possible
y <- "1" # this is preferred
y <- "1" # this is preferred traditionally
TRUE -> z # this works but is weird
# Refer to the Internet for the behaviors and preferences about them.
# LOOPS
# We've got for loops
@ -341,7 +339,7 @@ if (4 > 3) {
# FUNCTIONS
# Defined like so:
jiggle <- function(x) {
x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise
x = x + rnorm(1, sd=.1) # add in a bit of (controlled) noise
return(x)
}
# Called like any other R function:
@ -389,7 +387,7 @@ min(vec) # 8
sum(vec) # 38
# Some more nice built-ins:
5:15 # 5 6 7 8 9 10 11 12 13 14 15
seq(from=0, to=31337, by=1337)
seq(from = 0, to = 31337, by = 1337)
# =>
# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707
# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
@ -397,7 +395,7 @@ seq(from=0, to=31337, by=1337)
# TWO-DIMENSIONAL (ALL ONE CLASS)
# You can make a matrix out of entries all of the same type like so:
mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
mat <- matrix(nrow = 3, ncol = 2, c(1, 2, 3, 4, 5, 6))
mat
# =>
# [,1] [,2]
@ -405,13 +403,13 @@ mat
# [2,] 2 5
# [3,] 3 6
# Unlike a vector, the class of a matrix is "matrix", no matter what's in it
class(mat) # => "matrix"
class(mat) # "matrix"
# Ask for the first row
mat[1,] # 1 4
mat[1, ] # 1 4
# Perform operation on the first column
3 * mat[,1] # 3 6 9
3 * mat[, 1] # 3 6 9
# Ask for a specific cell
mat[3,2] # 6
mat[3, 2] # 6
# Transpose the whole matrix
t(mat)
@ -441,10 +439,10 @@ class(mat2) # matrix
# Again, note what happened!
# Because matrices must contain entries all of the same class,
# everything got converted to the character class
c(class(mat2[,1]), class(mat2[,2]))
c(class(mat2[, 1]), class(mat2[, 2]))
# rbind() sticks vectors together row-wise to make a matrix
mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
mat3 <- rbind(c(1, 2, 4, 5), c(6, 7, 0, 4))
mat3
# =>
# [,1] [,2] [,3] [,4]
@ -458,9 +456,9 @@ mat3
# This data structure is so useful for statistical programming,
# a version of it was added to Python in the package "pandas".
students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
c(3,2,2,1,0,-1),
c("H", "G", "G", "R", "S", "G"))
students <- data.frame(c("Cedric", "Fred", "George", "Cho", "Draco", "Ginny"),
c( 3, 2, 2, 1, 0, -1),
c( "H", "G", "G", "R", "S", "G"))
names(students) <- c("name", "year", "house") # name the columns
class(students) # "data.frame"
students
@ -485,8 +483,8 @@ dim(students) # 6 3
# There are many twisty ways to subset data frames, all subtly unalike
students$year # 3 2 2 1 0 -1
students[,2] # 3 2 2 1 0 -1
students[,"year"] # 3 2 2 1 0 -1
students[, 2] # 3 2 2 1 0 -1
students[, "year"] # 3 2 2 1 0 -1
# An augmented version of the data.frame structure is the data.table
# If you're working with huge or panel data, or need to merge a few data
@ -503,19 +501,19 @@ students # note the slightly different print-out
# 4: Cho 1 R
# 5: Draco 0 S
# 6: Ginny -1 G
students[name=="Ginny"] # get rows with name == "Ginny"
students[name == "Ginny"] # get rows with name == "Ginny"
# =>
# name year house
# 1: Ginny -1 G
students[year==2] # get rows with year == 2
students[year == 2] # get rows with year == 2
# =>
# name year house
# 1: Fred 2 G
# 2: George 2 G
# data.table makes merging two data sets easy
# let's make another data.table to merge with students
founders <- data.table(house=c("G","H","R","S"),
founder=c("Godric","Helga","Rowena","Salazar"))
founders <- data.table(house = c("G" , "H" , "R" , "S"),
founder = c("Godric", "Helga", "Rowena", "Salazar"))
founders
# =>
# house founder
@ -526,8 +524,8 @@ founders
setkey(students, house)
setkey(founders, house)
students <- founders[students] # merge the two data sets by matching "house"
setnames(students, c("house","houseFounderName","studentName","year"))
students[,order(c("name","year","house","houseFounderName")), with=F]
setnames(students, c("house", "houseFounderName", "studentName", "year"))
students[, order(c("name", "year", "house", "houseFounderName")), with = F]
# =>
# studentName year house houseFounderName
# 1: Fred 2 G Godric
@ -538,7 +536,7 @@ students[,order(c("name","year","house","houseFounderName")), with=F]
# 6: Draco 0 S Salazar
# data.table makes summary tables easy
students[,sum(year),by=house]
students[, sum(year), by = house]
# =>
# house V1
# 1: G 3
@ -571,7 +569,7 @@ students[studentName != "Draco"]
# 5: R Cho 1
# Using data.frame:
students <- as.data.frame(students)
students[students$house != "G",]
students[students$house != "G", ]
# =>
# house houseFounderName studentName year
# 4 H Helga Cedric 3
@ -583,13 +581,13 @@ students[students$house != "G",]
# Arrays creates n-dimensional tables
# All elements must be of the same type
# You can make a two-dimensional table (sort of like a matrix)
array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
array(c(c(1, 2, 4, 5), c(8, 9, 3, 6)), dim = c(2, 4))
# =>
# [,1] [,2] [,3] [,4]
# [1,] 1 4 8 3
# [2,] 2 5 9 6
# You can use array to make three-dimensional matrices too
array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
array(c(c(c(2, 300, 4), c(8, 9, 0)), c(c(5, 60, 0), c(66, 7, 847))), dim = c(3, 2, 2))
# =>
# , , 1
#
@ -609,7 +607,7 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
# Finally, R has lists (of vectors)
list1 <- list(time = 1:40)
list1$price = c(rnorm(40,.5*list1$time,4)) # random
list1$price = c(rnorm(40, .5*list1$time, 4)) # random
list1
# You can get items in the list like so
list1$time # one way
@ -719,7 +717,7 @@ summary(linearModel)$coefficients # another way to extract results
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
# time 0.4943490 0.06379348 7.74920901 2.440008e-09
summary(linearModel)$coefficients[,4] # the p-values
summary(linearModel)$coefficients[, 4] # the p-values
# =>
# (Intercept) time
# 9.234021e-01 2.440008e-09
@ -728,8 +726,7 @@ summary(linearModel)$coefficients[,4] # the p-values
# Logistic regression
set.seed(1)
list1$success = rbinom(length(list1$time), 1, .5) # random binary
glModel <- glm(success ~ time, data = list1,
family=binomial(link="logit"))
glModel <- glm(success ~ time, data = list1, family=binomial(link="logit"))
glModel # outputs result of logistic regression
# =>
# Call: glm(formula = success ~ time,
@ -745,8 +742,10 @@ glModel # outputs result of logistic regression
summary(glModel) # more verbose output from the regression
# =>
# Call:
# glm(formula = success ~ time,
# family = binomial(link = "logit"), data = list1)
# glm(
# formula = success ~ time,
# family = binomial(link = "logit"),
# data = list1)
# Deviance Residuals:
# Min 1Q Median 3Q Max
@ -780,7 +779,7 @@ plot(linearModel)
# Histograms!
hist(rpois(n = 10000, lambda = 5), col = "thistle")
# Barplots!
barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
barplot(c(1, 4, 5, 1, 2), names.arg = c("red", "blue", "purple", "green", "yellow"))
# GGPLOT2
# But these are not even the prettiest of R's plots
@ -788,10 +787,10 @@ barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
install.packages("ggplot2")
require(ggplot2)
?ggplot2
pp <- ggplot(students, aes(x=house))
pp <- ggplot(students, aes(x = house))
pp + geom_bar()
ll <- as.data.table(list1)
pp <- ggplot(ll, aes(x=time,price))
pp <- ggplot(ll, aes(x = time, price))
pp + geom_point()
# ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/)