4 C
London
Friday, December 20, 2024
HomeStatistics TutorialRHow to Add Suffix to Column Names in R (With Examples)

How to Add Suffix to Column Names in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following methods to add a suffix to column names in R:

Method 1: Add Suffix to All Column Names

colnames(df) my_suffix', sep = '_')

Method 2: Add Suffix to Specific Column Names

colnames(df)[c(1, 3)] my_suffix', sep = '_')

The following examples show how to use each method with the following data frame:

#create data frame
df frame(points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28))	

#view data frame
df

  points assists rebounds
1     99      33       30
2     90      28       28
3     86      31       24
4     88      39       24
5     95      34       28

Example 1: Add Suffix to All Column Names

The following code shows how to add the suffix ‘_total‘ to all column names:

#add suffix '_total' to all column names
colnames(df) total', sep = '_') 

#view updated data frame
df

  points_total assists_total rebounds_total
1           99            33             30
2           90            28             28
3           86            31             24
4           88            39             24
5           95            34             28

Notice that the suffix ‘_total‘ has been appended to the end of each column name.

Example 2: Add Suffix to Specific Column Names

The following code shows how to add the suffix ‘_total‘ to specific column names:

#add suffix '_total' to column names in index positions 1 and 3
colnames(df)[c(1, 3)] total', sep = '_') 

#view updated data frame
df

  points_total assists rebounds_total
1           99      33             30
2           90      28             28
3           86      31             24
4           88      39             24
5           95      34             28

Notice that the suffix ‘_total‘ has only been appended to the columns in index positions 1 and 3.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Loop Through Column Names in R
How to Rename a Single Column in R
How to Check if Column Exists in Data Frame in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories