Definition of vector in R

2019-05-27 11:47发布

问题:

I learnt that a vector is a sequence of data elements of the same basic type. Then what will we call a in the following code (as it contains both numeric and charater):

a = c(1,"b")
is.vector(a)
[1] TRUE

So is the definition of vector wrong? I referred this tutorial.

回答1:

The tutorial simplifies and that can cause confusion. Its definition describes "basic vector types", but there are also "generic vectors".

From the language definition (which you should study):

2.1.1 Vectors

Vectors can be thought of as contiguous cells containing data. Cells are accessed through indexing operations such as x[5]. More details are given in Indexing.

R has six basic (‘atomic’) vector types: logical, integer, real, complex, string (or character) and raw. The modes and storage modes for the different vector types are listed in the following table.

typeof    mode      storage.mode 
logical   logical   logical
integer   numeric   integer 
double    numeric   double 
complex   complex   complex
character character character 
raw       raw       raw 

Single numbers, such as 4.2, and strings, such as "four point two" are still vectors, of length 1; there are no more basic types. Vectors with length zero are possible (and useful).

2.1.2 Lists

Lists (“generic vectors”) are another kind of data storage. Lists have elements, each of which can contain any type of R object, i.e. the elements of a list do not have to be of the same type. List elements are accessed through three different indexing operations. These are explained in detail in Indexing.

Lists are vectors, and the basic vector types are referred to as atomic vectors where it is necessary to exclude lists.

From help("is.vector"):

If mode = "any", is.vector may return TRUE for the atomic modes, list and expression. For any mode, it will return FALSE if x has any attributes except names. [...]

(An expression is basically a list.)

Note that factors are not vectors; is.vector returns FALSE and as.vector converts a factor to a character vector for mode = "any".

Finally, as @Henrik points out, c coerces all arguments to the same type.



回答2:

Actually, in your example, the "1" will be viewed as a character by R.

a<-c(1,"b") typeof(a[1]) [1] "character"



标签: r vector