SlideShare a Scribd company logo
1 of 14
Download to read offline
R is a very flexible and powerful programming language, as well as a package that is written
using that language (and others like C). The following program demonstrates many of its basic
features. You can cut and paste it into R, or download the file that includes it from here. If you
run it line by line, many of its features will become clear. Both editions of R for SAS and SPSS
Users and R for Stata Users work through a version of this program line-by-line, showing the
output and explaining what R is doing.
# Filename: ProgrammingBasics.R
# ---Simple Calculations---
2 + 3
x <- 2
y <- 3
x + y
x * y
# ---Data Structures---
# Vectors
workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
print(workshop)
workshop
gender <- c("f", "f", "f", NA, "m", "m", "m", "m")
q1 <- c(1, 2, 2, 3, 4, 5, 5, 4)
q2 <- c(1, 1, 2, 1, 5, 4, 3, 5)
q3 <- c(5, 4, 4,NA, 2, 5, 4, 5)
q4 <- c(1, 1, 3, 3, 4, 5, 4, 5)
# Selecting Elements of Vectors
q1[5]
q1[ c(5, 6, 7, 8) ]
q1[5:8]
q1[gender == "m"]
mean( q1[ gender == "m" ], na.rm = TRUE)
# ---Factors---
# Numeric Factors
# First, as a vector
workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
workshop
table(workshop)
mean(workshop)
gender[workshop == 2]
# Now as a factor
workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
workshop <- factor(workshop)
workshop
table(workshop)
mean(workshop) #generates error now.
gender[workshop == 2]
gender[workshop == "2"]
# Recreate workshop, making it a factor
# including levels that don't yet exist.
workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
workshop <- factor(
workshop,
levels = c( 1, 2, 3, 4),
labels = c("R", "SAS", "SPSS", "Stata")
)
# Recreate it with just the levels it
# curently has.
workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
workshop <- factor(
workshop,
levels = c( 1, 2),
labels = c("R","SAS")
)
workshop
table(workshop)
gender[workshop == 2]
gender[workshop == "2"]
gender[workshop == "SAS"]
# Character factors
gender <- c("f", "f", "f", NA, "m", "m", "m", "m")
gender <- factor(
gender,
levels = c("m", "f"),
labels = c("Male", "Female")
)
gender
table(gender)
workshop[gender == "m"]
workshop[gender == "Male"]
# Recreate gender and make it a factor,
# keeping simpler m and f as labels.
gender <- c("f", "f", "f", NA, "m", "m", "m", "m")
gender <- factor(gender)
gender
# Data Frames
mydata <- data.frame(workshop, gender, q1, q2, q3, q4)
mydata
names(mydata)
row.names(mydata)
# Selecting components by index number
mydata[8, 6] #8th obs, 6th var
mydata[ , 6] #All obs, 6th var
mydata[ , 6][5:8] #6th var, obs 5:8
# Selecting components by name
mydata$q1
mydata$q1[5:8]
# Example renaming gender to sex while
# creating a data frame (left as a comment)
#
# mydata <- data.frame(workshop, sex = gender,
# q1, q2, q3, q4)
# Matrices
# Creating from vectors
mymatrix <- cbind(q1, q2, q3, q4)
mymatrix
dim(mymatrix)
# Creating from matrix function
# left as a comment so we keep
# version with names q1, q2...
#
# mymatrix <- matrix(
# c(1, 1, 5, 1,
# 2, 1, 4, 1,
# 2, 2, 4, 3,
# 3, 1, NA,3,
# 4, 5, 2, 4,
# 5, 4, 5, 5,
# 5, 3, 4, 4,
# 4, 5, 5, 5),
# nrow = 8, ncol = 4, byrow = TRUE)
# mymatrix
table(mymatrix)
mean(mymatrix, na.rm = TRUE)
cor(mymatrix, use = "pairwise")
# Selecting Subsets of Matrices
mymatrix[8, 4]
mymatrix[5:8, 3:4]
mymatrix[ ,4][1:4]
mymatrix$q4 # No good!
mymatrix[ ,"q4"]
# Matrix Algebra
mymatrixT <- t(mymatrix)
mymatrixT
# Lists
mylist <- list(workshop, gender,
q1, q2, q3, q4, mymatrix)
mylist
# List, this time adding names
mylist <- list(
workshop = workshop,
gender = gender,
q1 = q1,
q2 = q2,
q3 = q3,
q4 = q4,
mymatrix = mymatrix)
mylist
# Selecting components by index number.
mylist[[2]]
mylist[[2]][5:8]
mylist[2]
mylist[2][5:8] # Bad!
# Selecting components by name.
mylist$q1
mylist$mymatrix[5:8, 3:4]
# ---Saving Your Work---
ls()
objects() #same as ls()
save.image("myall.RData")
save(mydata, file = "mydata.RData")
# The 2nd approach is commented to keep
# the q variables for following examples.
# rm(x, y, workshop, gender, q1, q2, q3, q4, mylist)
# ls()
# save.image(file = "mydata.RData")
# ---Comments to Document Your Programs---
# This comment is on its own line, between functions.
workshop <- c(1, 2, 1, 2, #This comment is within the arguments.
1, 2, 1, 2) # And this is at the end.
# ---Comments to Document Your Objects---
comment(mydata) <- "Example data from R for SAS and SPSS Users"
comment(mydata)
# ---Controlling Functions---
# Controlling Functions with Arguments
help("mean")
mean(x = q3, trim = .25, na.rm = TRUE)
mean(na.rm = TRUE, x = q3, trim = .25)
mean(q3, .25, TRUE)
mean(q3, t = .25, na.rm = TRUE)
mean(1, 2, 3)
mean( c(1, 2, 3) )
mean( 1:3 )
# Controlling Functions With Formulas
lm( q4 ~ q1 + q2 + q3, data = mydata )
t.test(q1 ~ gender, data = mydata)
t.test( q1[ which(gender == "Female") ],
q1[ which(gender == "Male") ],
data = mydata) # Data ignored!
# Controlling Functions with Extractor Functions
lm( q4 ~ q1 + q2 + q3, data = mydata )
myModel <- lm( q4 ~ q1 + q2 + q3, data = mydata )
class(myModel)
summary(myModel)
# How Much Output Is There?
print(mymodel)
mode(myModel)
class(myModel)
names(myModel)
print( unclass(myModel) )
myModel$coefficients
class( myModel$coefficients )
barplot( myModel$coefficients )
# ---Writing Your Own Functions (Macros)---
myvar <- c(1, 2, 3, 4, 5)
# A bad function.
mystats <- function(x) {
mean(x, na.rm = TRUE)
sd(x, na.rm = TRUE)
}
mystats(myvar)
# A good function that just prints.
mystats <- function(x) {
print( mean(x, na.rm = TRUE) )
print( sd(x, na.rm = TRUE) )
}
mystats(myvar)
# A function with vector output.
mystats <- function(x) {
mymean <- mean(x, na.rm = TRUE)
mysd <- sd(x, na.rm = TRUE)
c(mean = mymean, sd = mysd )
}
mystats(myvar)
myVector <- mystats(myvar)
myVector
# A function with list output.
mystats <- function(x) {
myinput <- x
mymean <- mean(x, na.rm = TRUE)
mysd <- sd(x, na.rm = TRUE)
list(data = myinput, mean = mymean, sd = mysd)
}
mystats(myvar)
myStatlist <- mystats(myvar)
myStatlist
mystats
save(mydata, mymatrix, mylist, mystats,
file = "myWorkspace.RData")
Solution
R is a very flexible and powerful programming language, as well as a package that is written
using that language (and others like C). The following program demonstrates many of its basic
features. You can cut and paste it into R, or download the file that includes it from here. If you
run it line by line, many of its features will become clear. Both editions of R for SAS and SPSS
Users and R for Stata Users work through a version of this program line-by-line, showing the
output and explaining what R is doing.
# Filename: ProgrammingBasics.R
# ---Simple Calculations---
2 + 3
x <- 2
y <- 3
x + y
x * y
# ---Data Structures---
# Vectors
workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
print(workshop)
workshop
gender <- c("f", "f", "f", NA, "m", "m", "m", "m")
q1 <- c(1, 2, 2, 3, 4, 5, 5, 4)
q2 <- c(1, 1, 2, 1, 5, 4, 3, 5)
q3 <- c(5, 4, 4,NA, 2, 5, 4, 5)
q4 <- c(1, 1, 3, 3, 4, 5, 4, 5)
# Selecting Elements of Vectors
q1[5]
q1[ c(5, 6, 7, 8) ]
q1[5:8]
q1[gender == "m"]
mean( q1[ gender == "m" ], na.rm = TRUE)
# ---Factors---
# Numeric Factors
# First, as a vector
workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
workshop
table(workshop)
mean(workshop)
gender[workshop == 2]
# Now as a factor
workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
workshop <- factor(workshop)
workshop
table(workshop)
mean(workshop) #generates error now.
gender[workshop == 2]
gender[workshop == "2"]
# Recreate workshop, making it a factor
# including levels that don't yet exist.
workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
workshop <- factor(
workshop,
levels = c( 1, 2, 3, 4),
labels = c("R", "SAS", "SPSS", "Stata")
)
# Recreate it with just the levels it
# curently has.
workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
workshop <- factor(
workshop,
levels = c( 1, 2),
labels = c("R","SAS")
)
workshop
table(workshop)
gender[workshop == 2]
gender[workshop == "2"]
gender[workshop == "SAS"]
# Character factors
gender <- c("f", "f", "f", NA, "m", "m", "m", "m")
gender <- factor(
gender,
levels = c("m", "f"),
labels = c("Male", "Female")
)
gender
table(gender)
workshop[gender == "m"]
workshop[gender == "Male"]
# Recreate gender and make it a factor,
# keeping simpler m and f as labels.
gender <- c("f", "f", "f", NA, "m", "m", "m", "m")
gender <- factor(gender)
gender
# Data Frames
mydata <- data.frame(workshop, gender, q1, q2, q3, q4)
mydata
names(mydata)
row.names(mydata)
# Selecting components by index number
mydata[8, 6] #8th obs, 6th var
mydata[ , 6] #All obs, 6th var
mydata[ , 6][5:8] #6th var, obs 5:8
# Selecting components by name
mydata$q1
mydata$q1[5:8]
# Example renaming gender to sex while
# creating a data frame (left as a comment)
#
# mydata <- data.frame(workshop, sex = gender,
# q1, q2, q3, q4)
# Matrices
# Creating from vectors
mymatrix <- cbind(q1, q2, q3, q4)
mymatrix
dim(mymatrix)
# Creating from matrix function
# left as a comment so we keep
# version with names q1, q2...
#
# mymatrix <- matrix(
# c(1, 1, 5, 1,
# 2, 1, 4, 1,
# 2, 2, 4, 3,
# 3, 1, NA,3,
# 4, 5, 2, 4,
# 5, 4, 5, 5,
# 5, 3, 4, 4,
# 4, 5, 5, 5),
# nrow = 8, ncol = 4, byrow = TRUE)
# mymatrix
table(mymatrix)
mean(mymatrix, na.rm = TRUE)
cor(mymatrix, use = "pairwise")
# Selecting Subsets of Matrices
mymatrix[8, 4]
mymatrix[5:8, 3:4]
mymatrix[ ,4][1:4]
mymatrix$q4 # No good!
mymatrix[ ,"q4"]
# Matrix Algebra
mymatrixT <- t(mymatrix)
mymatrixT
# Lists
mylist <- list(workshop, gender,
q1, q2, q3, q4, mymatrix)
mylist
# List, this time adding names
mylist <- list(
workshop = workshop,
gender = gender,
q1 = q1,
q2 = q2,
q3 = q3,
q4 = q4,
mymatrix = mymatrix)
mylist
# Selecting components by index number.
mylist[[2]]
mylist[[2]][5:8]
mylist[2]
mylist[2][5:8] # Bad!
# Selecting components by name.
mylist$q1
mylist$mymatrix[5:8, 3:4]
# ---Saving Your Work---
ls()
objects() #same as ls()
save.image("myall.RData")
save(mydata, file = "mydata.RData")
# The 2nd approach is commented to keep
# the q variables for following examples.
# rm(x, y, workshop, gender, q1, q2, q3, q4, mylist)
# ls()
# save.image(file = "mydata.RData")
# ---Comments to Document Your Programs---
# This comment is on its own line, between functions.
workshop <- c(1, 2, 1, 2, #This comment is within the arguments.
1, 2, 1, 2) # And this is at the end.
# ---Comments to Document Your Objects---
comment(mydata) <- "Example data from R for SAS and SPSS Users"
comment(mydata)
# ---Controlling Functions---
# Controlling Functions with Arguments
help("mean")
mean(x = q3, trim = .25, na.rm = TRUE)
mean(na.rm = TRUE, x = q3, trim = .25)
mean(q3, .25, TRUE)
mean(q3, t = .25, na.rm = TRUE)
mean(1, 2, 3)
mean( c(1, 2, 3) )
mean( 1:3 )
# Controlling Functions With Formulas
lm( q4 ~ q1 + q2 + q3, data = mydata )
t.test(q1 ~ gender, data = mydata)
t.test( q1[ which(gender == "Female") ],
q1[ which(gender == "Male") ],
data = mydata) # Data ignored!
# Controlling Functions with Extractor Functions
lm( q4 ~ q1 + q2 + q3, data = mydata )
myModel <- lm( q4 ~ q1 + q2 + q3, data = mydata )
class(myModel)
summary(myModel)
# How Much Output Is There?
print(mymodel)
mode(myModel)
class(myModel)
names(myModel)
print( unclass(myModel) )
myModel$coefficients
class( myModel$coefficients )
barplot( myModel$coefficients )
# ---Writing Your Own Functions (Macros)---
myvar <- c(1, 2, 3, 4, 5)
# A bad function.
mystats <- function(x) {
mean(x, na.rm = TRUE)
sd(x, na.rm = TRUE)
}
mystats(myvar)
# A good function that just prints.
mystats <- function(x) {
print( mean(x, na.rm = TRUE) )
print( sd(x, na.rm = TRUE) )
}
mystats(myvar)
# A function with vector output.
mystats <- function(x) {
mymean <- mean(x, na.rm = TRUE)
mysd <- sd(x, na.rm = TRUE)
c(mean = mymean, sd = mysd )
}
mystats(myvar)
myVector <- mystats(myvar)
myVector
# A function with list output.
mystats <- function(x) {
myinput <- x
mymean <- mean(x, na.rm = TRUE)
mysd <- sd(x, na.rm = TRUE)
list(data = myinput, mean = mymean, sd = mysd)
}
mystats(myvar)
myStatlist <- mystats(myvar)
myStatlist
mystats
save(mydata, mymatrix, mylist, mystats,
file = "myWorkspace.RData")

More Related Content

Similar to R is a very flexible and powerful programming language, as well as a.pdf

RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programmingYanchang Zhao
 
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxINFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxcarliotwaycave
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In RRsquared Academy
 
M12 random forest-part01
M12 random forest-part01M12 random forest-part01
M12 random forest-part01Raman Kannan
 
Day 1d R structures & objects: matrices and data frames.pptx
Day 1d   R structures & objects: matrices and data frames.pptxDay 1d   R structures & objects: matrices and data frames.pptx
Day 1d R structures & objects: matrices and data frames.pptxAdrien Melquiond
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavSeminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavVyacheslav Arbuzov
 
A quick introduction to R
A quick introduction to RA quick introduction to R
A quick introduction to RAngshuman Saha
 
data frames.pptx
data frames.pptxdata frames.pptx
data frames.pptxRacksaviR
 
A brief introduction to apply functions
A brief introduction to apply functionsA brief introduction to apply functions
A brief introduction to apply functionsNIKET CHAURASIA
 
The Very ^ 2 Basics of R
The Very ^ 2 Basics of RThe Very ^ 2 Basics of R
The Very ^ 2 Basics of RWinston Chen
 
R Programming.pptx
R Programming.pptxR Programming.pptx
R Programming.pptxkalai75
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Phil Calçado
 
Ejercicios de estilo en la programación
Ejercicios de estilo en la programaciónEjercicios de estilo en la programación
Ejercicios de estilo en la programaciónSoftware Guru
 

Similar to R is a very flexible and powerful programming language, as well as a.pdf (20)

RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programming
 
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxINFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docx
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In R
 
R
RR
R
 
M12 random forest-part01
M12 random forest-part01M12 random forest-part01
M12 random forest-part01
 
Day 1d R structures & objects: matrices and data frames.pptx
Day 1d   R structures & objects: matrices and data frames.pptxDay 1d   R structures & objects: matrices and data frames.pptx
Day 1d R structures & objects: matrices and data frames.pptx
 
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov VyacheslavSeminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
 
A quick introduction to R
A quick introduction to RA quick introduction to R
A quick introduction to R
 
data frames.pptx
data frames.pptxdata frames.pptx
data frames.pptx
 
Session 02
Session 02Session 02
Session 02
 
A brief introduction to apply functions
A brief introduction to apply functionsA brief introduction to apply functions
A brief introduction to apply functions
 
The Very ^ 2 Basics of R
The Very ^ 2 Basics of RThe Very ^ 2 Basics of R
The Very ^ 2 Basics of R
 
R Programming.pptx
R Programming.pptxR Programming.pptx
R Programming.pptx
 
Programming in R
Programming in RProgramming in R
Programming in R
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)
 
DataMapper
DataMapperDataMapper
DataMapper
 
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
 
Ejercicios de estilo en la programación
Ejercicios de estilo en la programaciónEjercicios de estilo en la programación
Ejercicios de estilo en la programación
 

More from annikasarees

You will want to look at electronegativity differ.pdf
                     You will want to look at electronegativity differ.pdf                     You will want to look at electronegativity differ.pdf
You will want to look at electronegativity differ.pdfannikasarees
 
Well 1-Heptanol is a straight chained 7 carbon mo.pdf
                     Well 1-Heptanol is a straight chained 7 carbon mo.pdf                     Well 1-Heptanol is a straight chained 7 carbon mo.pdf
Well 1-Heptanol is a straight chained 7 carbon mo.pdfannikasarees
 
The rings cannot attach to each other on C atoms .pdf
                     The rings cannot attach to each other on C atoms .pdf                     The rings cannot attach to each other on C atoms .pdf
The rings cannot attach to each other on C atoms .pdfannikasarees
 
Waters bent structure leads to its polar nature.pdf
                     Waters bent structure leads to its polar nature.pdf                     Waters bent structure leads to its polar nature.pdf
Waters bent structure leads to its polar nature.pdfannikasarees
 
The given set of values cannot be represented as .pdf
                     The given set of values cannot be represented as .pdf                     The given set of values cannot be represented as .pdf
The given set of values cannot be represented as .pdfannikasarees
 
Solution containing HCN and NaCN in ions form as .pdf
                     Solution containing HCN and NaCN in ions form as .pdf                     Solution containing HCN and NaCN in ions form as .pdf
Solution containing HCN and NaCN in ions form as .pdfannikasarees
 
moles = molarity x volume = 6 molL x (51000) L .pdf
                     moles = molarity x volume = 6 molL x (51000) L .pdf                     moles = molarity x volume = 6 molL x (51000) L .pdf
moles = molarity x volume = 6 molL x (51000) L .pdfannikasarees
 
Molarity = moles volume(liter) Moles = molarity.pdf
                     Molarity = moles volume(liter)  Moles = molarity.pdf                     Molarity = moles volume(liter)  Moles = molarity.pdf
Molarity = moles volume(liter) Moles = molarity.pdfannikasarees
 
lone pairs of electrons also occupy the orbitals .pdf
                     lone pairs of electrons also occupy the orbitals .pdf                     lone pairs of electrons also occupy the orbitals .pdf
lone pairs of electrons also occupy the orbitals .pdfannikasarees
 
What is the relationship between Accounting and an Accounting inform.pdf
What is the relationship between Accounting and an Accounting inform.pdfWhat is the relationship between Accounting and an Accounting inform.pdf
What is the relationship between Accounting and an Accounting inform.pdfannikasarees
 
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdf
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdfYes,all macromolecule are passed from nuclear pore envelope to cytop.pdf
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdfannikasarees
 
The transport of sodium ions and glucose into the cell is through sy.pdf
The transport of sodium ions and glucose into the cell is through sy.pdfThe transport of sodium ions and glucose into the cell is through sy.pdf
The transport of sodium ions and glucose into the cell is through sy.pdfannikasarees
 
the issue of camera and cell phone privecy is importent many cell ph.pdf
the issue of camera and cell phone privecy is importent many cell ph.pdfthe issue of camera and cell phone privecy is importent many cell ph.pdf
the issue of camera and cell phone privecy is importent many cell ph.pdfannikasarees
 
Statement showing distribution of income to XavierThus answer will.pdf
Statement showing distribution of income to XavierThus answer will.pdfStatement showing distribution of income to XavierThus answer will.pdf
Statement showing distribution of income to XavierThus answer will.pdfannikasarees
 
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdfSummary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdfannikasarees
 
SolutionBy observing the graph , the graph the given function is .pdf
SolutionBy observing the graph , the graph the given function is .pdfSolutionBy observing the graph , the graph the given function is .pdf
SolutionBy observing the graph , the graph the given function is .pdfannikasarees
 
please give the name of author so that i can give u solution manual .pdf
please give the name of author so that i can give u solution manual .pdfplease give the name of author so that i can give u solution manual .pdf
please give the name of author so that i can give u solution manual .pdfannikasarees
 
PetTest.javaimport java.util.Scanner; public class PetTest {.pdf
PetTest.javaimport java.util.Scanner; public class PetTest {.pdfPetTest.javaimport java.util.Scanner; public class PetTest {.pdf
PetTest.javaimport java.util.Scanner; public class PetTest {.pdfannikasarees
 
Kentucks nickname for tommy luck isB. The d--d little cussWho .pdf
Kentucks nickname for tommy luck isB. The d--d little cussWho .pdfKentucks nickname for tommy luck isB. The d--d little cussWho .pdf
Kentucks nickname for tommy luck isB. The d--d little cussWho .pdfannikasarees
 

More from annikasarees (20)

You will want to look at electronegativity differ.pdf
                     You will want to look at electronegativity differ.pdf                     You will want to look at electronegativity differ.pdf
You will want to look at electronegativity differ.pdf
 
Well 1-Heptanol is a straight chained 7 carbon mo.pdf
                     Well 1-Heptanol is a straight chained 7 carbon mo.pdf                     Well 1-Heptanol is a straight chained 7 carbon mo.pdf
Well 1-Heptanol is a straight chained 7 carbon mo.pdf
 
The rings cannot attach to each other on C atoms .pdf
                     The rings cannot attach to each other on C atoms .pdf                     The rings cannot attach to each other on C atoms .pdf
The rings cannot attach to each other on C atoms .pdf
 
Waters bent structure leads to its polar nature.pdf
                     Waters bent structure leads to its polar nature.pdf                     Waters bent structure leads to its polar nature.pdf
Waters bent structure leads to its polar nature.pdf
 
The given set of values cannot be represented as .pdf
                     The given set of values cannot be represented as .pdf                     The given set of values cannot be represented as .pdf
The given set of values cannot be represented as .pdf
 
Solution containing HCN and NaCN in ions form as .pdf
                     Solution containing HCN and NaCN in ions form as .pdf                     Solution containing HCN and NaCN in ions form as .pdf
Solution containing HCN and NaCN in ions form as .pdf
 
moles = molarity x volume = 6 molL x (51000) L .pdf
                     moles = molarity x volume = 6 molL x (51000) L .pdf                     moles = molarity x volume = 6 molL x (51000) L .pdf
moles = molarity x volume = 6 molL x (51000) L .pdf
 
Molarity = moles volume(liter) Moles = molarity.pdf
                     Molarity = moles volume(liter)  Moles = molarity.pdf                     Molarity = moles volume(liter)  Moles = molarity.pdf
Molarity = moles volume(liter) Moles = molarity.pdf
 
lone pairs of electrons also occupy the orbitals .pdf
                     lone pairs of electrons also occupy the orbitals .pdf                     lone pairs of electrons also occupy the orbitals .pdf
lone pairs of electrons also occupy the orbitals .pdf
 
What is the relationship between Accounting and an Accounting inform.pdf
What is the relationship between Accounting and an Accounting inform.pdfWhat is the relationship between Accounting and an Accounting inform.pdf
What is the relationship between Accounting and an Accounting inform.pdf
 
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdf
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdfYes,all macromolecule are passed from nuclear pore envelope to cytop.pdf
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdf
 
The transport of sodium ions and glucose into the cell is through sy.pdf
The transport of sodium ions and glucose into the cell is through sy.pdfThe transport of sodium ions and glucose into the cell is through sy.pdf
The transport of sodium ions and glucose into the cell is through sy.pdf
 
the issue of camera and cell phone privecy is importent many cell ph.pdf
the issue of camera and cell phone privecy is importent many cell ph.pdfthe issue of camera and cell phone privecy is importent many cell ph.pdf
the issue of camera and cell phone privecy is importent many cell ph.pdf
 
Statement showing distribution of income to XavierThus answer will.pdf
Statement showing distribution of income to XavierThus answer will.pdfStatement showing distribution of income to XavierThus answer will.pdf
Statement showing distribution of income to XavierThus answer will.pdf
 
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdfSummary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
 
SolutionBy observing the graph , the graph the given function is .pdf
SolutionBy observing the graph , the graph the given function is .pdfSolutionBy observing the graph , the graph the given function is .pdf
SolutionBy observing the graph , the graph the given function is .pdf
 
F(-) Sol.pdf
                     F(-)                                      Sol.pdf                     F(-)                                      Sol.pdf
F(-) Sol.pdf
 
please give the name of author so that i can give u solution manual .pdf
please give the name of author so that i can give u solution manual .pdfplease give the name of author so that i can give u solution manual .pdf
please give the name of author so that i can give u solution manual .pdf
 
PetTest.javaimport java.util.Scanner; public class PetTest {.pdf
PetTest.javaimport java.util.Scanner; public class PetTest {.pdfPetTest.javaimport java.util.Scanner; public class PetTest {.pdf
PetTest.javaimport java.util.Scanner; public class PetTest {.pdf
 
Kentucks nickname for tommy luck isB. The d--d little cussWho .pdf
Kentucks nickname for tommy luck isB. The d--d little cussWho .pdfKentucks nickname for tommy luck isB. The d--d little cussWho .pdf
Kentucks nickname for tommy luck isB. The d--d little cussWho .pdf
 

Recently uploaded

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 

Recently uploaded (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 

R is a very flexible and powerful programming language, as well as a.pdf

  • 1. R is a very flexible and powerful programming language, as well as a package that is written using that language (and others like C). The following program demonstrates many of its basic features. You can cut and paste it into R, or download the file that includes it from here. If you run it line by line, many of its features will become clear. Both editions of R for SAS and SPSS Users and R for Stata Users work through a version of this program line-by-line, showing the output and explaining what R is doing. # Filename: ProgrammingBasics.R # ---Simple Calculations--- 2 + 3 x <- 2 y <- 3 x + y x * y # ---Data Structures--- # Vectors workshop <- c(1, 2, 1, 2, 1, 2, 1, 2) print(workshop) workshop gender <- c("f", "f", "f", NA, "m", "m", "m", "m") q1 <- c(1, 2, 2, 3, 4, 5, 5, 4) q2 <- c(1, 1, 2, 1, 5, 4, 3, 5) q3 <- c(5, 4, 4,NA, 2, 5, 4, 5) q4 <- c(1, 1, 3, 3, 4, 5, 4, 5) # Selecting Elements of Vectors q1[5] q1[ c(5, 6, 7, 8) ] q1[5:8] q1[gender == "m"] mean( q1[ gender == "m" ], na.rm = TRUE) # ---Factors--- # Numeric Factors # First, as a vector workshop <- c(1, 2, 1, 2, 1, 2, 1, 2) workshop table(workshop)
  • 2. mean(workshop) gender[workshop == 2] # Now as a factor workshop <- c(1, 2, 1, 2, 1, 2, 1, 2) workshop <- factor(workshop) workshop table(workshop) mean(workshop) #generates error now. gender[workshop == 2] gender[workshop == "2"] # Recreate workshop, making it a factor # including levels that don't yet exist. workshop <- c(1, 2, 1, 2, 1, 2, 1, 2) workshop <- factor( workshop, levels = c( 1, 2, 3, 4), labels = c("R", "SAS", "SPSS", "Stata") ) # Recreate it with just the levels it # curently has. workshop <- c(1, 2, 1, 2, 1, 2, 1, 2) workshop <- factor( workshop, levels = c( 1, 2), labels = c("R","SAS") ) workshop table(workshop) gender[workshop == 2] gender[workshop == "2"] gender[workshop == "SAS"] # Character factors gender <- c("f", "f", "f", NA, "m", "m", "m", "m") gender <- factor( gender, levels = c("m", "f"),
  • 3. labels = c("Male", "Female") ) gender table(gender) workshop[gender == "m"] workshop[gender == "Male"] # Recreate gender and make it a factor, # keeping simpler m and f as labels. gender <- c("f", "f", "f", NA, "m", "m", "m", "m") gender <- factor(gender) gender # Data Frames mydata <- data.frame(workshop, gender, q1, q2, q3, q4) mydata names(mydata) row.names(mydata) # Selecting components by index number mydata[8, 6] #8th obs, 6th var mydata[ , 6] #All obs, 6th var mydata[ , 6][5:8] #6th var, obs 5:8 # Selecting components by name mydata$q1 mydata$q1[5:8] # Example renaming gender to sex while # creating a data frame (left as a comment) # # mydata <- data.frame(workshop, sex = gender, # q1, q2, q3, q4) # Matrices # Creating from vectors mymatrix <- cbind(q1, q2, q3, q4) mymatrix dim(mymatrix) # Creating from matrix function # left as a comment so we keep # version with names q1, q2...
  • 4. # # mymatrix <- matrix( # c(1, 1, 5, 1, # 2, 1, 4, 1, # 2, 2, 4, 3, # 3, 1, NA,3, # 4, 5, 2, 4, # 5, 4, 5, 5, # 5, 3, 4, 4, # 4, 5, 5, 5), # nrow = 8, ncol = 4, byrow = TRUE) # mymatrix table(mymatrix) mean(mymatrix, na.rm = TRUE) cor(mymatrix, use = "pairwise") # Selecting Subsets of Matrices mymatrix[8, 4] mymatrix[5:8, 3:4] mymatrix[ ,4][1:4] mymatrix$q4 # No good! mymatrix[ ,"q4"] # Matrix Algebra mymatrixT <- t(mymatrix) mymatrixT # Lists mylist <- list(workshop, gender, q1, q2, q3, q4, mymatrix) mylist # List, this time adding names mylist <- list( workshop = workshop, gender = gender, q1 = q1, q2 = q2, q3 = q3, q4 = q4,
  • 5. mymatrix = mymatrix) mylist # Selecting components by index number. mylist[[2]] mylist[[2]][5:8] mylist[2] mylist[2][5:8] # Bad! # Selecting components by name. mylist$q1 mylist$mymatrix[5:8, 3:4] # ---Saving Your Work--- ls() objects() #same as ls() save.image("myall.RData") save(mydata, file = "mydata.RData") # The 2nd approach is commented to keep # the q variables for following examples. # rm(x, y, workshop, gender, q1, q2, q3, q4, mylist) # ls() # save.image(file = "mydata.RData") # ---Comments to Document Your Programs--- # This comment is on its own line, between functions. workshop <- c(1, 2, 1, 2, #This comment is within the arguments. 1, 2, 1, 2) # And this is at the end. # ---Comments to Document Your Objects--- comment(mydata) <- "Example data from R for SAS and SPSS Users" comment(mydata) # ---Controlling Functions--- # Controlling Functions with Arguments help("mean") mean(x = q3, trim = .25, na.rm = TRUE) mean(na.rm = TRUE, x = q3, trim = .25) mean(q3, .25, TRUE) mean(q3, t = .25, na.rm = TRUE) mean(1, 2, 3) mean( c(1, 2, 3) )
  • 6. mean( 1:3 ) # Controlling Functions With Formulas lm( q4 ~ q1 + q2 + q3, data = mydata ) t.test(q1 ~ gender, data = mydata) t.test( q1[ which(gender == "Female") ], q1[ which(gender == "Male") ], data = mydata) # Data ignored! # Controlling Functions with Extractor Functions lm( q4 ~ q1 + q2 + q3, data = mydata ) myModel <- lm( q4 ~ q1 + q2 + q3, data = mydata ) class(myModel) summary(myModel) # How Much Output Is There? print(mymodel) mode(myModel) class(myModel) names(myModel) print( unclass(myModel) ) myModel$coefficients class( myModel$coefficients ) barplot( myModel$coefficients ) # ---Writing Your Own Functions (Macros)--- myvar <- c(1, 2, 3, 4, 5) # A bad function. mystats <- function(x) { mean(x, na.rm = TRUE) sd(x, na.rm = TRUE) } mystats(myvar) # A good function that just prints. mystats <- function(x) { print( mean(x, na.rm = TRUE) ) print( sd(x, na.rm = TRUE) ) } mystats(myvar) # A function with vector output.
  • 7. mystats <- function(x) { mymean <- mean(x, na.rm = TRUE) mysd <- sd(x, na.rm = TRUE) c(mean = mymean, sd = mysd ) } mystats(myvar) myVector <- mystats(myvar) myVector # A function with list output. mystats <- function(x) { myinput <- x mymean <- mean(x, na.rm = TRUE) mysd <- sd(x, na.rm = TRUE) list(data = myinput, mean = mymean, sd = mysd) } mystats(myvar) myStatlist <- mystats(myvar) myStatlist mystats save(mydata, mymatrix, mylist, mystats, file = "myWorkspace.RData") Solution R is a very flexible and powerful programming language, as well as a package that is written using that language (and others like C). The following program demonstrates many of its basic features. You can cut and paste it into R, or download the file that includes it from here. If you run it line by line, many of its features will become clear. Both editions of R for SAS and SPSS Users and R for Stata Users work through a version of this program line-by-line, showing the output and explaining what R is doing. # Filename: ProgrammingBasics.R # ---Simple Calculations--- 2 + 3 x <- 2 y <- 3 x + y
  • 8. x * y # ---Data Structures--- # Vectors workshop <- c(1, 2, 1, 2, 1, 2, 1, 2) print(workshop) workshop gender <- c("f", "f", "f", NA, "m", "m", "m", "m") q1 <- c(1, 2, 2, 3, 4, 5, 5, 4) q2 <- c(1, 1, 2, 1, 5, 4, 3, 5) q3 <- c(5, 4, 4,NA, 2, 5, 4, 5) q4 <- c(1, 1, 3, 3, 4, 5, 4, 5) # Selecting Elements of Vectors q1[5] q1[ c(5, 6, 7, 8) ] q1[5:8] q1[gender == "m"] mean( q1[ gender == "m" ], na.rm = TRUE) # ---Factors--- # Numeric Factors # First, as a vector workshop <- c(1, 2, 1, 2, 1, 2, 1, 2) workshop table(workshop) mean(workshop) gender[workshop == 2] # Now as a factor workshop <- c(1, 2, 1, 2, 1, 2, 1, 2) workshop <- factor(workshop) workshop table(workshop) mean(workshop) #generates error now. gender[workshop == 2] gender[workshop == "2"] # Recreate workshop, making it a factor # including levels that don't yet exist. workshop <- c(1, 2, 1, 2, 1, 2, 1, 2)
  • 9. workshop <- factor( workshop, levels = c( 1, 2, 3, 4), labels = c("R", "SAS", "SPSS", "Stata") ) # Recreate it with just the levels it # curently has. workshop <- c(1, 2, 1, 2, 1, 2, 1, 2) workshop <- factor( workshop, levels = c( 1, 2), labels = c("R","SAS") ) workshop table(workshop) gender[workshop == 2] gender[workshop == "2"] gender[workshop == "SAS"] # Character factors gender <- c("f", "f", "f", NA, "m", "m", "m", "m") gender <- factor( gender, levels = c("m", "f"), labels = c("Male", "Female") ) gender table(gender) workshop[gender == "m"] workshop[gender == "Male"] # Recreate gender and make it a factor, # keeping simpler m and f as labels. gender <- c("f", "f", "f", NA, "m", "m", "m", "m") gender <- factor(gender) gender # Data Frames mydata <- data.frame(workshop, gender, q1, q2, q3, q4)
  • 10. mydata names(mydata) row.names(mydata) # Selecting components by index number mydata[8, 6] #8th obs, 6th var mydata[ , 6] #All obs, 6th var mydata[ , 6][5:8] #6th var, obs 5:8 # Selecting components by name mydata$q1 mydata$q1[5:8] # Example renaming gender to sex while # creating a data frame (left as a comment) # # mydata <- data.frame(workshop, sex = gender, # q1, q2, q3, q4) # Matrices # Creating from vectors mymatrix <- cbind(q1, q2, q3, q4) mymatrix dim(mymatrix) # Creating from matrix function # left as a comment so we keep # version with names q1, q2... # # mymatrix <- matrix( # c(1, 1, 5, 1, # 2, 1, 4, 1, # 2, 2, 4, 3, # 3, 1, NA,3, # 4, 5, 2, 4, # 5, 4, 5, 5, # 5, 3, 4, 4, # 4, 5, 5, 5), # nrow = 8, ncol = 4, byrow = TRUE) # mymatrix table(mymatrix)
  • 11. mean(mymatrix, na.rm = TRUE) cor(mymatrix, use = "pairwise") # Selecting Subsets of Matrices mymatrix[8, 4] mymatrix[5:8, 3:4] mymatrix[ ,4][1:4] mymatrix$q4 # No good! mymatrix[ ,"q4"] # Matrix Algebra mymatrixT <- t(mymatrix) mymatrixT # Lists mylist <- list(workshop, gender, q1, q2, q3, q4, mymatrix) mylist # List, this time adding names mylist <- list( workshop = workshop, gender = gender, q1 = q1, q2 = q2, q3 = q3, q4 = q4, mymatrix = mymatrix) mylist # Selecting components by index number. mylist[[2]] mylist[[2]][5:8] mylist[2] mylist[2][5:8] # Bad! # Selecting components by name. mylist$q1 mylist$mymatrix[5:8, 3:4] # ---Saving Your Work--- ls() objects() #same as ls()
  • 12. save.image("myall.RData") save(mydata, file = "mydata.RData") # The 2nd approach is commented to keep # the q variables for following examples. # rm(x, y, workshop, gender, q1, q2, q3, q4, mylist) # ls() # save.image(file = "mydata.RData") # ---Comments to Document Your Programs--- # This comment is on its own line, between functions. workshop <- c(1, 2, 1, 2, #This comment is within the arguments. 1, 2, 1, 2) # And this is at the end. # ---Comments to Document Your Objects--- comment(mydata) <- "Example data from R for SAS and SPSS Users" comment(mydata) # ---Controlling Functions--- # Controlling Functions with Arguments help("mean") mean(x = q3, trim = .25, na.rm = TRUE) mean(na.rm = TRUE, x = q3, trim = .25) mean(q3, .25, TRUE) mean(q3, t = .25, na.rm = TRUE) mean(1, 2, 3) mean( c(1, 2, 3) ) mean( 1:3 ) # Controlling Functions With Formulas lm( q4 ~ q1 + q2 + q3, data = mydata ) t.test(q1 ~ gender, data = mydata) t.test( q1[ which(gender == "Female") ], q1[ which(gender == "Male") ], data = mydata) # Data ignored! # Controlling Functions with Extractor Functions lm( q4 ~ q1 + q2 + q3, data = mydata ) myModel <- lm( q4 ~ q1 + q2 + q3, data = mydata ) class(myModel) summary(myModel) # How Much Output Is There?
  • 13. print(mymodel) mode(myModel) class(myModel) names(myModel) print( unclass(myModel) ) myModel$coefficients class( myModel$coefficients ) barplot( myModel$coefficients ) # ---Writing Your Own Functions (Macros)--- myvar <- c(1, 2, 3, 4, 5) # A bad function. mystats <- function(x) { mean(x, na.rm = TRUE) sd(x, na.rm = TRUE) } mystats(myvar) # A good function that just prints. mystats <- function(x) { print( mean(x, na.rm = TRUE) ) print( sd(x, na.rm = TRUE) ) } mystats(myvar) # A function with vector output. mystats <- function(x) { mymean <- mean(x, na.rm = TRUE) mysd <- sd(x, na.rm = TRUE) c(mean = mymean, sd = mysd ) } mystats(myvar) myVector <- mystats(myvar) myVector # A function with list output. mystats <- function(x) { myinput <- x mymean <- mean(x, na.rm = TRUE) mysd <- sd(x, na.rm = TRUE)
  • 14. list(data = myinput, mean = mymean, sd = mysd) } mystats(myvar) myStatlist <- mystats(myvar) myStatlist mystats save(mydata, mymatrix, mylist, mystats, file = "myWorkspace.RData")