Lists and Data Frames
Lists and Data Frames
Lists
R lists are objects containing ordered
collections of objects (components).
$elev
[1] 1200
$month
[1] "N" "D" "J"
$snowdepth
[1] 6 21 44
An object can be added to a list by passing it as a new component of the
list
> snowyday=c(4,5,6)
> x[5] <- list(snowyday)
>
>x
$station
[1] "Vinadio"
$elev
[1] 1200
$month
[1] "N" "D" "J"
$snowdepth
[1] 6 21 44
[[5]]
[1] 4 5 6
To join together different lists, say x, y and z, and
create a new list xyz, the concatenation function c()
can be used.
N.B.:
The double bracket [[ ]] is used to select components of
the list
The single bracket [ ] is used to select elements of the i
component
Example:
x[[4]] [2,3] will give: 21,44
Data frames
Data frames are objects sharing many of the properties of
matrices and of lists:
they are collections of objects (vectors, matrices, lists or other
data frames) of differing types (numeric, logical, character,
complex);
Vector structures must all have the same length (if not they
are recycled), matrix structures must all have the same row
size.
Generating a data frame
name_dataframe$name_component
the double brackets [[ ]]
name_dataframe [[ 1 ]]
the functions:
attach(name_dataframe)
...
detach():
Through the function attach() it is possible to access the
components of a data frame (list) without quoting the name of the
data frame (list) each time.
The attach() function appends the name of the data frame to the
searching path.
stationX$wind wind
This function detaches the name of the data frame from the
searching path, so the components are no longer visible with
their names only.
Again they can be accessed only with the list notation:
stationX$wind
ATTENTION
After the function attach() is called, all the
operations on the components of the data
frame do not affect the original data frame,
but a copy of its components.
> attach(df)
> z<-x+y
> detach(df)
> df
xyz
1130
2220
3310
df$z <-df$x+df$y
> df
xyz
1134
2224
3314
Testing and coercing
If you need to verify the mode or the structure of an object you can
use the function is.():
is.mode(object)
is.structure(object)
is.integer(x) is.vector(x)
is.double(x) is.matrix(x)
is.na(x) is.array(x)
is.numeric(x) is.list(x)
is.character(x) is.data.frame
is.complex(x) is.ts(x)
is.logic(x)
as.integer(x) as.vector(x)
as.double(x) as.matrix(x)
as.na(x) as.array(x)
as.numeric(x) as.list(x)
as.character(x) as.data.frame
as.complex(x) as.ts(x)
as.logic(x)
Example
> a<- 1:5
>a
[1] 1 2 3 4 5
> is.vector(a)
[1] TRUE
> a<-as.matrix(a)
>a
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
> is.matrix(a)
[1] TRUE
> is.integer(a)
[1] TRUE