📜  index in - R 编程语言(1)

📅  最后修改于: 2023-12-03 14:42:05.997000             🧑  作者: Mango

Indexing in R Programming Language

R programming language is widely used for statistical computing, data analysis, and graphical visualization. One of the essential concepts in R programming language is indexing, which is used to access and manipulate elements of arrays, matrices, and data frames.

Indexing 1-Dimensional Arrays

In R programming language, 1-dimensional arrays are called vectors. They can be created using the c() function. Here is an example of creating a vector of integers from 1 to 5:

my_vector <- c(1, 2, 3, 4, 5)

To access an element at a particular index, we use square brackets [ ]. For example, to access the third element of our my_vector array, we would use the following code:

my_vector[3]

The output should be 3.

We can also modify the value of an element at a particular index using the assignment operator = or <-. For example, to change the fourth element of our my_vector array to 10, we would use the following code:

my_vector[4] <- 10
Indexing 2-Dimensional Arrays

In R programming language, 2-dimensional arrays are called matrices. They can be created using the matrix() function. Here is an example of creating a 3x3 matrix of random integers:

my_matrix <- matrix(sample.int(9), ncol = 3)

To access an element at a particular row and column, we use square brackets [ , ]. For example, to access the element in the second row and third column of our my_matrix array, we would use the following code:

my_matrix[2, 3]

The output should be a random integer between 1 and 9.

We can also modify the value of an element at a particular row and column using the assignment operator = or <-. For example, to change the element in the first row and second column of our my_matrix array to 5, we would use the following code:

my_matrix[1, 2] <- 5
Indexing Data Frames

In R programming language, data frames are used to store data in tabular format. They can be created using the data.frame() function. Here is an example of creating a simple data frame of names and ages:

my_data <- data.frame(names = c("Alice", "Bob", "Charlie"), ages = c(25, 30, 35))

To access a column of a data frame, we use the $ operator. For example, to access the age column of our my_data data frame, we would use the following code:

my_data$ages

To access a particular element of a data frame, we use square brackets [ , ]. For example, to access the age of Charlie in our my_data data frame, we would use the following code:

my_data[3, "ages"]

The output should be 35.

Conclusion

Indexing is a fundamental concept in R programming language that allows programmers to manipulate and access elements of arrays, matrices, and data frames. By understanding indexing, programmers can efficiently work with data in R and create sophisticated data analyses and visualizations.