Creating a Vector

Vectors are variables with one or more values of the same type: logical, integer, real, complex, string (or character) or raw. A variable with a single value (say 4.3) is often known as a scalar, but in R a scalar is a vector of length 1. Vectors could have length 0 and this can be useful in writing functions:

y<-4.3

z<-y[-1]

length(z)

[1] 0

Values can be assigned to vectors in many different ways. They can be generated by R: here the vector called y gets the sequence of integer values 10 to 16 using : (colon), the sequence-generating operator,

y<- 10:16

You can type the values into the command line, using the concatenation function c,

y <- c(10, 11, 12, 13, 14, 15, 16)

or you can enter the numbers from the keyboard one at a time using scan:

y<- scan()

1: 10

2: 11

3: 12

4: 13

5: 14

6: 15

7: 16

8:

Read 7 items

pressing the Enter key instead of entering a number to indicate that data input is complete. However, the commonest way to allocate values to a vector is to read the data from an external file, using read.table (p. 98). Note that read.table will convert character variables into factors, so if you do not want this to happen, you will need to say so (p. 100). In order to refer to a vector by name with an R session, you need to attach the dataframe containing the vector (p. 18). Alternatively, you can refer to the dataframe name and the vector name within it, using the element name operator $ like this: dataframe$y

One of the most important attributes ...

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.