Select variables of data frame in R

Select variables of data frame in R, we will learn how to use the select and rename functions of the dplyr package to select and rename variables in R.

We will use the dplyr package to manipulate a data frame, which is a fundamental data structure in R.

The tutorial consists of two examples that demonstrate how to use the select and rename functions to select and rename variables.

Creation of Example Data

We will use the following data frame for the examples of this tutorial:

data <- data.frame(x1 = 1:3,
                   x2 = LETTERS[1:3],
                   x3 = 5)
data
#   x1 x2 x3
# 1  1  A  5
# 2  2  B  5
# 3  3  C  5

This data frame contains three rows and three columns. We will use this data frame to demonstrate how to use the select and rename functions.

Example 1: Extract Variables with select Function

The select function is used to extract specific variables from a data frame. We can use the select function to extract the variables x1 and x3 from our data frame:

How to copy files in R » Data Science Tutorials

select(data, c(x1, x3))
#   x1 x3
# 1  1  5
# 2  2  5
# 3  3  5

This will return a subset of our original data frame containing only the two selected columns.

select(data, c(x1, -x3))
# x1
# 1 1
# 2 2
# 3 3

Example 2: Change Variable Name with rename Function

The rename function is used to change the column names of specific variables. We can use the rename function to change the name of the first column of our data frame from x1 to x1_new:

Extract columns of data frame in R » Data Science Tutorials

dplyr::rename(data, x1_new = x1)
#   x1_new x2 x3
# 1      1  A  5
# 2      2  B  5
# 3      3  C  5

This will return a new data frame with the modified column names.

Conclusion

In this tutorial, we have learned how to use the select and rename functions of the dplyr package to select and rename variables in R.

We have demonstrated how to use these functions to extract specific variables from a data frame and change the column names of specific variables. With these functions, you can easily manipulate and analyze your data in R.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

5 × three =