IntroductiontoRProgrammingLanguage
Opensourceprogramminglanguage
ModeledafterS&SplusdevelopedatAT&Tlabsinlate1980s
RprojectwasstartedbyRobertGentlemanandRossIhakaDept.
ofStatistics,UniversityofAuckland1995
CurrentlymaintainedbyRcoredevelopmentteam
Internationalteamofvolunteerdevelopers(since1997)
RURLs
[Link]/
[Link]
CRAN:TheComprehensiveRArchiveNetwork
[Link]/
Linux:sudoaptgetinstallrbasecore
GettinghelpfromRconsole
o [Link]()
o help(topic)
o ?topic
o ??topic
MoreonHelp&Packages
Rmemoryarchitectureworkspace
GettingFamiliarwithR
HowtouseRforsimplemath
Howtostoreresultsofcalculationsforfutureuse
Howtocreatedataobjectsfromkeyboardorexternalfiles
Howtoseetheobjectsthatarereadyforuse
Howtolookatthedifferenttypesofdataobjects
Howtomakedifferenttypesofdataobjects
Howtosaveyourwork
Howtousepreviouscommandsinthehistory
HowtouseRforsimplemath
>3+5
>12+3/45+3*8
>(12+3/45)+3*8
>pi*2^3sqrt(4)
>factorial(4)
>log(2,10)
>log(2,base=10)
>log10(2)
>log(2)
Rignoresspaces
Howtostoreresultsofcalculationsforfutureuse
>x=3+5
>x
>y=12+3/45+3*8
>y
>z=(12+3/45)+3*8
>z
>A<6+8##nospacebetween<&
>a##Riscasesensitive
>A
Identifiers:(Google'sRStyleGuide)
([Link]
Don'tuseunderscores(_)orhyphens()inidentifiers.
Thepreferredformforvariablenamesisalllowercaseletters
andwordsseparatedwithdots([Link]),
butvariableNameisalsoaccepted;
functionnameshaveinitialcapitallettersandnodots
(FunctionName);constantsarenamedlikefunctionsbutwith
aninitialk.
[Link],variableNameisaccepted
GOOD:[Link]
OK:avgClicks
BAD:avg_Clicks
UsingCcommand(Combineorconcatenation)formakingdata
>data1=c(3,6,9,12,78,34,5,7,7)##numericaldata
>[Link]=c(Mon,Tue,Wed)##Textdata;
##Singleordoublequotebothok
##copy/pasteintoRconsolemaynotwork
>[Link]=c([Link],Thu,Fri)
Usingscancommandformakingdata
>data3=scan()##dataseparatedbySpace/PressEntertwicetoexit
1:4578
5:294
8:3
9:
Read8items
>data3
[1]45782943
>d3=scan(what=character)
1:mon
2:tue
3:wedthu
5:
Read4items
>d3
[1]"mon""tue""wed""thu"
>d3[2]
[1]"tue"
>d3[2]='mon'
>d3
[1]"mon""mon""wed""thu"
>d3[6]='sat'
>d3
[1]"mon""mon""wed""thu"NA"sat"
>d3[2]='tue'
>d3[5]='fri'
>d3
[1]"mon""tue""wed""thu""fri""sat"
ConceptofWorkingDirectory
>getwd()
[1]"C:/Users/nkonar/Documents"
>setwd('D:/RSW')
>dir()##workingdirectorylisting
>ls()##Workspacelistingofobjects
>rm(object)
>rm(list=ls())##SpringCleaning
ReadingdatafromFile
Settheworkingdirectorytofilelocation
>setwd('D:/RSW/WD')
>getwd()
[1]"D:/RSW/WD"
>dir()
[1]"[Link]""DiningAtSFO""LatentViewDPL""[Link]"
"[Link]""[Link]""[Link]"
>tcdata=[Link]('[Link]',header=T,sep=',')
(tcdata=[Link]('[Link]',header=T,sep=','))
>ls()
[1]"tcdata"
>str(tcdata)
'[Link]':10obs.of9variables:
$Id:int12345678910
Othervariables;
Howtoaccessindividualdataelements/variables
>tcdata$Price
[1]13500137501395014950137501295016900186002150012950
>tcdata$Price[7]=20000
>tcdata$Price
[1]13500137501395014950137501295020000186002150012950
Thischangehashappenedinworkspaceonlynotinthefile.
Howtomakeitpermanent?
[Link]/[Link]
>[Link](tcdata,file='[Link]',[Link]=FALSE,sep=',')
[Link],RaddsoneIDcolumninthebeginningoffile.
[Link]=FALSEoption
>[Link](tcdata,file='[Link]',[Link]=TRUE)##totest
TypesofDataItem:
Vector
Matrix
DataFrame
List
Vectors:
>x=c(1,2,3,4,56)
>x
>x[2]
>x=c(3,4,NA,5)
>mean(x)
[1]NA
>mean(x,[Link]=T)
[1]4
>x=c(3,4,NULL,5)
>mean(x)
[1]4
Vectors:
>y=c(x,c(1,5),x)
>length(x)
>length(y)
Thereareusefulmethodstocreatelongvectorswhoseelementsareinarithmetic
progression:
>x=1:20
>x
Trymin(),max(),mean(),range(),sum(),summary(),sd()functions
Ifthecommondifferenceisnot1or1thenwecanusetheseqfunction
>y=seq(2,5,0.3)
>y
[1][Link].[Link].[Link]
>length(y)
[1]11
Vectors:
>x=1:5
>mean(x)
[1]3
>x
[1]12345
>x^2
[1]1491625
>x+1
[1]23456
>2*x
[1]246810
>exp(sqrt(x))
[1]2.7182824.1132505.6522347.3890569.356469
Itisveryeasytoadd/subtract/multiply/dividetwovectorsentrybyentry.
>y=c(0,3,4,0)
>x+y
[1]15745
Warningmessage:
Inx+y:longerobjectlengthisnotamultipleofshorterobjectlength
>y=c(0,3,4,0,9)
>x+y
[1]157414
>x=1:6
>y=c(9,8)
>x+y
[1]101012121414
Matrices:
Samedatatype/modenumber,character,logical
[Link]<matrix(vector,nrow=r,ncol=c,byrow=FALSE,dimnames=list(char
vectorrownames,charvectorcolnames))
##dimnamesisoptionalargument,provideslabelsforrows&columns.
>y<matrix(1:20,nrow=4,ncol=5)
>A=matrix(c(1,2,3,4),nrow=2,byrow=T)
>A
>A=matrix(c(1,2,3,4),ncol=2)
>B=matrix(2:7,nrow=2)
>C=matrix(5:2,ncol=2)
>mr<matrix(1:20,nrow=5,ncol=4,byrow=T)
>mc<matrix(1:20,nrow=5,ncol=4)
>mr
>mc
>dim(B)#dimension
>nrow(B)
>ncol(B)
>A+C
>AC
>A%*%C#matrixmultiplication
>A*C#entrywisemultiplication
>t(A)##Transpose
>A[1,2]
>A[1,]
>B[1,c(2,3)]
>B[,1]
MatrixAlgebra:[Link]
Lists
VectorsandmatricesinRaretwowaystoworkwithacollectionofobjects.
[Link]
differentkindsofobjects.
Oneentryinalistmaybeanumber,whilethenextisamatrix,whileathird
isacharacterstring(like"HelloR!").
[Link]
mustknowhowtounpackalistusingthe$symbol
>x=list(name="ArunPatel",nationality="Indian",height=5.5,
grades=c(95,45,80))
>names(x)
>x$name
>x$hei#abbrevsareOK
>x$grades
>x$g[2]
DataFrame:
Adataframeismoregeneralthanamatrix,inthatdifferentcolumnscan
havedifferentmodes(numeric,character,factor,etc.).
ThisissimilartoSASandSPSSdatasets.
>d<c(1,2,3,4)
>e<c("red","white","red",NA)
>f<c(TRUE,TRUE,TRUE,FALSE)
>myframe<[Link](d,e,f)
>names(myframe)<c("ID","Color","Passed")#variablenames
>myframe
>myframe[1:3,]#rows1,2,3ofdataframe
>myframe[,1:2]#col1,2ofdataframe
>myframe[c("ID","Color")]#columnsIDandcolorfromdataframe
>myframe$ID#variableIDinthedataframe
DataStructures:
ListandDataFrame:
ListsarebyfarthemostflexibledatastructureinR.
Theycanbeseenasacollectionofelementswithoutanyrestrictionon
theclass,lengthorstructureofeachelement.
Theonlythingyouneedtotakecareof,isthatyoudon'tgivetwo
[Link],andR
doesn'tgiveerrorsforthat:
>X<list(a=1,b=2,a=3)
>X$a
[1]1
Dataframesarelistsaswell,buttheyhaveafewrestrictions:
youcan'tusethesamenamefortwodifferentvariables
allelementsofadataframearevectors
allelementsofadataframehaveanequallength.
Duetotheserestrictionsandtheresultingtwodimensionalstructure,
dataframescanmimicksomeofthebehaviourofmatrices.
[Link]'tdothatwith
lists,asarowisundefinedthere.
Allthisimpliesthatyoushoulduseadataframeforanydatasetthatfits
inthattwodimensionalstructure.
Essentially,youusedataframesforanydatasetwhereacolumncoincides
withavariableandarowcoincideswithasingleobservationinthebroad
senseoftheword.
Forallotherstructures,listsarethewaytogo.
Notethatifyouwantanestedstructure,[Link]
elementsofalistcanbeliststhemselves,youcancreateveryflexible
structuredobjects.
Factor:
TellRthatavariableisnominalbymakingitafactor.
Thefactorstoresthenominalvaluesasavectorofintegersintherange[
1...k](wherekisthenumberofuniquevaluesinthenominalvariable),
Aninternalvectorofcharacterstrings(theoriginalvalues)mappedto
theseintegers.
#variablegenderwith20"male"entriesand
#30"female"entries
>gender<c(rep("male",20),rep("female",30))
>gender<factor(gender)
#storesgenderas201sand302sandassociates
#1=female,2=maleinternally(alphabetically)
#Rnowtreatsgenderasanominalvariable
>summary(gender)
Function:
>g=function(x,y)(x+2*y)/3
>g(1,2)
>g(2,1)
RInterface:
[Link]
RIntro:
[Link]
CodeSchool(OReilly):
[Link]
q()
[Link]=[Link]("D:\\RSW\\[Link]",header=T,sep=",")
>summary([Link])
lmod1=lm(Price~Age_08_04,data=[Link])
>lmod1
Call:
lm(formula=Price~Age_08_04,data=[Link])
Coefficients:
(Intercept)Age_08_04
21353199
>summary(lmod1)
Call:
lm(formula=Price~Age_08_04+KM,data=[Link])
Residuals:
Min1QMedian3QMax
6598.41144.1161.81038.111828.7
Coefficients:
[Link](>|t|)
(Intercept)2.137e+041.816e+02117.671<2e16***
Age_08_041.751e+024.661e+0037.559<2e16***
KM1.768e022.109e038.382<2e16***
source("D:\\RSW\\[Link]")