-1

Given

    RAnswers <- c(0:10,NA) ;
    SAnswers <- c(0:20,NA) ;
    WAnswers <- c(0:30,NA) ;

    answers.list <- list(RAnswers,SAnswers,WAnswers) ;

    class(RAnswers) ;
    class(answers.list) ;
    class(answers.list[1]) ;
    class(answers.list[[1]]) ;

the results are

    > class(RAnswers) ;
    [1] "integer"
    > class(answers.list) ;
    [1] "list"
    > class(answers.list[1]) ;
    [1] "list"
    > class(answers.list[[1]]) ;
    [1] "integer"

why does class(answers.list[1]) return "list" ?

Keith John Hutchison
  • 4,955
  • 11
  • 46
  • 64
  • 3
    For a list `[]` subsets the list, while [[]] extracts the element from the list. When you subset an object, you often maintain the class of the original object, though this is not always the case. See my attempt at an answer [here](http://stackoverflow.com/questions/36777567/is-there-a-logical-way-to-think-about-list-indexing/36815401#36815401). – lmo Apr 30 '16 at 19:07
  • 1
    Could you write that up as an answer @imo. It's clear and concise. – Keith John Hutchison Apr 30 '16 at 19:16

1 Answers1

1

In lists, [ is used to subset the list. Because of this, [ returns a list of a different length. The [[ function is used to extract elements or items from the list.

Subsetting often returns an object of the same class in R, although matrices can move to a simpler class with [M,N] subsetting when either M or N is some expression that results in a vector of length 1 (also true for data.frames where N results in a vector of length 1).

lmo
  • 37,904
  • 9
  • 56
  • 69