How to create a simple list

#1
I was wondering if someone can help me understand lists.
I have a table that I need to convert to a list. There are 2 columns and 2 observations.

Column 1 is "Names" and Column 2 is "Classes".
For the first observation:
Column1/Row1 is "James", and Column2/Row1 is "Math, Physics, Chemistry".

Here's my code:
Code:
a <-list(name = "James", Courses = c("Math", "Physics", "Chemistry"))
b <- list (name = "Peter", Courses = c("English", "History", "Sociology"))
Student_Data = list(a,b)
If someone asks me to make a list, is this how I do it? Am I suppose to be able to extract individual courses out of this list? if so, I can't seem to do it.
 

trinker

ggplot2orBust
#2
What you have is a nested list of lists. So yes that's one way to make a list.

Code:
## Your data
a <-list(name = "James", Courses = c("Math", "Physics", "Chemistry"))
b <- list (name = "Peter", Courses = c("English", "History", "Sociology"))
Student_Data = list(a,b)
You can access your Courses like this (this is one way). Lists in R are typically not the go to. There are uses but I'm not sure this is one of them.

Code:
lapply(Student_Data, function(x) `[[`(x, 'Courses'))

## [[1]]
## [1] "Math"      "Physics"   "Chemistry"
##
## [[2]]
## [1] "English"   "History"   "Sociology"
You could make it tabular and the it's easier to extract things from the data. Here's an example using the tidyverse package.

Code:
library(tidyverse)

## reconstructing the nested list as a data.frame
Student_Data_Tabular <- Student_Data %>%
    transpose() %>%
    as_tibble() %>%
    tidyr::unnest(name) %>%
    tidyr::unnest(Courses)

## get all courses
Student_Data_Tabular %>%
    pull(Courses)

## [1] "Math"      "Physics"   "Chemistry" "English"   "History"   "Sociology"


## count of all courses in desc order
Student_Data_Tabular %>%
    count(Courses) %>%
    arrange(desc(n))

## # A tibble: 6 x 2
##   Courses       n
##   <chr>     <int>
## 1 Chemistry     1
## 2 English       1
## 3 History       1
## 4 Math          1
## 5 Physics       1
## 6 Sociology     1


## Grab records for just those named james
Student_Data_Tabular %>%
    filter(name %in% 'James')

## # A tibble: 3 x 2
##   name  Courses 
##   <chr> <chr>   
## 1 James Math    
## 2 James Physics 
## 3 James Chemistry

## grab any record for those that took a MAth or English
Student_Data_Tabular %>%
    filter(Courses %in% c('Math', 'English'))

## # A tibble: 3 x 2
##   name  Courses 
##   <chr> <chr>   
## 1 James Math    
## 2 James Physics 
## 3 James Chemistry