11.3 Factors and lists

  • Factors
    • Class: "factor"
    • factor(): Create an unordered factor
    • ordered(): Create an ordered factor
    • A way to store data for categorical (nominal/ordinal) variables
    • Vector with attributes
    • levels(): Display categories
    • as.numeric(): Convert factor to numeric vector


  • Lists
    • Class: "list"
    • list(): Create a list
    • Collections of arbitrary objects
    • Have a certain length and list elements can carry names
    • list$switzerland: Access element switzerland of the list list
    • list[2]: Access second element of the list list
    • Sometimes results of estimations are stored as lists
  • We’ll see more object classes later on


11.3.1 Example: Factors and lists

# Q: How do i get help for the function factor()?

# Create factor (nominal variable)
f <- factor(rep(1:2,10),levels=c(1,2), labels=c("SPD", "CDU"))

# Q: How do I go about to understand what happens in the function?

f
levels(f)
as.numeric(f)


# Create factor (ordinal variable)
o <- ordered(rep(1:3,10),levels=c(1,2,3), labels=c("low", "medium", "high"))
o
as.numeric(o)
as.character(o)


# Create a list
participants <- list(Teacher= "Rudi", 
                     Women = c("Daniela","Johanna"),
                     Men = c("Simon", "Peter", "usw."))

participants
length(participants)

# Access elements or subsets of that list
participants$Teacher
participants[1]
participants[[1]]
participants[["Teacher"]]

# Q: How can I access the list element "Women"?
# Q: How can i access the Johanna who is in the element "Women"?


11.3.2 Exercise: Factors and lists (HOMEWORK)

  1. Create a list mylist with two elements. The first element first contains the numbers 5 to 105. The second element second contains the numbers -1 to -50. Create another vector x that contains the 70th value of the first element of mylist and the 30th element of the second element of mylist.
  2. Create a list anotherlist with four elements: A, B, C, D. A contains the number 2. B contains a vector with the number 1 to 10. C contains a character vector with the names “Bernd” “Hans” “Peter”. D contains a vector with the numbers 1 to 100.
  3. Extract the third Element C from the list you just generated and save it in a new object names.
  4. Extract the vector elements 25 to 35 out of the fourth element D of the list and save them in an object names xyz.
  5. Create vector using the following code: test <- rep(1:10,10). Convert test to an ordered factor. Check which categories the factor has and whether it’s ordered.


11.3.3 Solution: Objects: Factors and lists