[R] R's list data structure

Sarah Goslee sarah.goslee at gmail.com
Fri Feb 17 21:30:41 CET 2012


HI Ajay,

On Fri, Feb 17, 2012 at 3:20 PM, Ajay Askoolum <aa2e72e at yahoo.co.uk> wrote:
> Given
>
> dayOfWeekName<-c("Mon","Tue","Wed","Thu","Fri","Sat","Sun");
> dayOfWeekOrdinal<-c(1,2,3,4,5,6,0);
> dayOfWeekWorkDay<-c(TRUE,TRUE,TRUE,TRUE,TRUE,FALSE,FALSE);
>
> weekProfile<-list(dow=dayOfWeekName,dowI=dayOfWeekOrdinal,dowW=dayOfWeekWorkDay)
>
>
> 1. How can I conditionally get dow, dowI, and dowW from weekProfile?
>
> If another 'arrangement' of this list object will make this task easier, please advise.

> 2. What is the point of the list object?
>
> I know that when mixed data types need to be held together, then the only option is to use the list data structure.

In your particular case, where all list components are the same length and are
associated with each other in order, a special type of list called a data frame
is easier to work with.

weekProfile<- data.frame(dow=dayOfWeekName,dowI=dayOfWeekOrdinal,dowW=dayOfWeekWorkDay)
> weekProfile
  dow dowI  dowW
1 Mon    1  TRUE
2 Tue    2  TRUE
3 Wed    3  TRUE
4 Thu    4  TRUE
5 Fri    5  TRUE
6 Sat    6 FALSE
7 Sun    0 FALSE

I'm not sure what kind of conditional you want, but this can easily be done
with subset() or [

> weekProfile[weekProfile$dowW ,]
  dow dowI dowW
1 Mon    1 TRUE
2 Tue    2 TRUE
3 Wed    3 TRUE
4 Thu    4 TRUE
5 Fri    5 TRUE

A regular list is excellent for holding diverse kinds of data, for example 10
lm() objects, or a series of data frames.

In a list, the third element of component 1 may not have anything whatsoever
to do with the third element of component 2.

In a data frame, rows are related.

> If I were to hold recurring (Name, Salary, DateOfBirth) (i.e. character, integer and date values) in a list object, what would be the 'optimal' arrangement?

Data frame.

> Would that be as the components of weekProfile above? Or will this be better.
>
> Either:
>
> personalDetail<- list(rbind(c(Name,Salary,DateOfBirth),c(Name,Salary,DateOfBirth)));


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list