Rename Variable Names in List of Data Frames in R (Example Code)

In this tutorial, I’ll explain how to modify the variable names of data frames in a list in R.

Introduction of Example Data

data_list <- list(data.frame(a1 = 1:4,    # Construct list with data frames
                             a2 = 4:1),
                  data.frame(b1 = 11:14,
                             b2 = 14:11),
                  data.frame(c1 = 21:24,
                             c2 = 24:21))
data_list
# [[1]]
#   a1 a2
# 1  1  4
# 2  2  3
# 3  3  2
# 4  4  1
# 
# [[2]]
#   b1 b2
# 1 11 14
# 2 12 13
# 3 13 12
# 4 14 11
# 
# [[3]]
#   c1 c2
# 1 21 24
# 2 22 23
# 3 23 22
# 4 24 21

Example: Renaming the Data Frame Columns in a List Object

data_list_upd <- lapply(data_list,        # Change column names
                        setNames,
                        c("col1", "col2"))
data_list_upd
# [[1]]
#   col1 col2
# 1    1    4
# 2    2    3
# 3    3    2
# 4    4    1
# 
# [[2]]
#   col1 col2
# 1   11   14
# 2   12   13
# 3   13   12
# 4   14   11
# 
# [[3]]
#   col1 col2
# 1   21   24
# 2   22   23
# 3   23   22
# 4   24   21

Further Resources

Please find some related R programming tutorials on topics such as lists, variables, and merging below:

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top