官术网_书友最值得收藏!

Vectors

A vector is an object that holds a collection of various data elements in R, though they are limited because everything inside of a vector must all belong to the same variable type. You can create a vector using the method c(), for example:

 vector_example <- c(1, 2, 3, 4)

In the above snippet, the method c() creates a vector named vector_example. It will have a length of four and be of class numeric. You use c() to create any type of vector by inputting a comma-separated list of the items you'd like inside the vector. If you input different classes of objects inside the vector (such as numeric and character strings), it will default to one of them.

In the following code, we can see an example where the class of the vector is a character because of the B in position 2:

vector_example_2 <- c(1, "B", 3)
class(vector_example_2)

Output: The preceding code provides the following output:

To access a certain item in the vector, you can use indexing. R is a 1-indexed language, meaning all counting starts at 1 (versus other languages, such as Python, which are 0-indexed—that is, in Python, the first element of the array is said to be at the 0th position).

The first item in a vector can be accessed using vector[1], and so on. If the index doesn't exist in the vector, R will simply output an NA, which is R's default way of indicating a missing value. We'll cover missing values in R at length in Chapter 3, Data Management.

Let us now use c() to create a vector, examine its class and type, and access different elements of the vector using vector indexing. Follow the steps given below:

  1. Create the vectors twenty and alphabet using the following code:
twenty <- c(1:20)
alphabet <- c(letters)
  1. Check the class and type of twenty and alphabet using class() and typeof(), respectively, as follows:
class(twenty)
typeof(twenty)

class(alphabet)
typeof(alphabet)
  1. Find the numbers at the following positions in twenty using vector indexing:
twenty[5]
twenty[17]
twenty[25]
  1. Find the letters at the following positions in the alphabet using vector indexing:
alphabet[6]
alphabet[23]
alphabet[33]

Output: The code we write will be as follows:

twenty <- c(1:20)
alphabet <- c(letters)
class(twenty)
typeof(twenty)
class(alphabet)
typeof(alphabet)
twenty[5]
twenty[17]
twenty[25]
alphabet[6]
alphabet[23]
alphabet[33]

The output we get after executing it is as follows:

主站蜘蛛池模板: 浦江县| 巴林右旗| 华池县| 海口市| 青铜峡市| 五家渠市| 彰武县| 新巴尔虎左旗| 石棉县| 余姚市| 河津市| 台州市| 康平县| 诏安县| 衢州市| 青田县| 车险| 多伦县| 时尚| 武定县| 得荣县| 台江县| 琼结县| 武冈市| 济源市| 拉萨市| 蕉岭县| 东宁县| 罗城| 公主岭市| 乳源| 石阡县| 乌拉特后旗| 阿克| 灵石县| 扶风县| 新田县| 天津市| 崇义县| 龙川县| 九龙县|