LEC 1.6
Matrices : 2-dimension vectors
Data frames
A data.frame shares the properties of matrices and lists; unlike a matrix a data.frame can have columns with different types of data
Recycling
R is vectorized and recycles elements (e.g., for creating the x column in the previous slide); another example we already saw : 就是相乘而已
Reading a data.frame from a file
LEC 1.7 The apply family
>> the apply family serve as an alternatives to loops (similarto list comprehension in python; and map in functionalprogramming) 循环的替代品
>> lapply : 返回lists
>> sapply : 返回vectors,output是lapply的简化版
>> apply :
apply(X,MARGIN,FUN)
这个MARGIN的位置格式为:MARGIN=1 (for row) / MARGIN=2 (for column)/ MARGIN=c(1,2) (for both)
FUN的位置是写函数名的:例如mean ...
>> mapply : g更复杂化的sapply
LEC 1.8 Financial time series and quantmod
Time series
A time series is a sequence of measurements indexed by time. The measurements can be
• at regular intervals
• or unevenly spaced
Time series analysis is prominent(重要的) in Economics and Finance
The quantmod package
LEC 1.9 The xts package
Times and dates in R
There are many time and date classes in R, e.g.
• POSIXct, POSIXlt, Date, chron, timeData, yearmon, yearqtr
We will use mainly
• Date (date)
• POSIXct (date-time)
Times and Dates
Sequences of dates
xts and zoo
xts extends zoo
>> zoo
Class of indexed totally ordered observations
• particularly aimed at irregular time series 无规律的时间序列
• must contain data of one type (numeric/logical/character)
• zoo's key design goals are
• independence from particular index/date/time class;
• consistency with ts and base R by providing methods to extend standard generics (e.g. plot)
>> xts
• Time-based extension of zoo which is popular and robust
• Requires indexing bases on recognised time-based class,
e.g. POSIXct, Date, chron, timeData, yearmon, yearqtr
• time-based subsetting
• hidden attributes (accessed with xtsAttributes())
• smart conversion tools
• time-based tools like fast aggregation
>> Create an xts object
Options include:
• as.xts()
• xts() constructor
Example :