Home > Software engineering >  How to add the position index as the suffix into the columns in R?
How to add the position index as the suffix into the columns in R?

Time:09-27

I just have a data.frame like this:

             x           y            z
1          5.1         3.5          1.4
2          4.9         3.0          1.4
3          4.7         3.2          1.3
4          4.6         3.1          1.5
5          5.0         3.6          1.4
6          5.4         3.9          1.7

How can I change the column name to this:

           x_1         y_2          z_3
1          5.1         3.5          1.4
2          4.9         3.0          1.4
3          4.7         3.2          1.3
4          4.6         3.1          1.5
5          5.0         3.6          1.4
6          5.4         3.9          1.7

Thanks!

CodePudding user response:

df <- data.frame(x = 1:3, y = 1:3, z = 1:3)
colnames(df) <- paste0(colnames(df), "_", seq(ncol(df)))

#  x_1 y_2 z_3
#1   1   1   1
#2   2   2   2
#3   3   3   3

Or if you prefer paste:

paste(colnames(df), seq(ncol(df)), sep = "_")

Also works with seq_along:

paste(colnames(df), seq_along(df), sep = "_")

CodePudding user response:

dplyr approach using rename_with like this:

df <- read.table(text = "             x           y            z
1          5.1         3.5          1.4
2          4.9         3.0          1.4
3          4.7         3.2          1.3
4          4.6         3.1          1.5
5          5.0         3.6          1.4
6          5.4         3.9          1.7", header = TRUE)

library(dplyr)
df %>% 
  rename_with( ~ paste0(.x, '_', seq_along(.x)))
#>   x_1 y_2 z_3
#> 1 5.1 3.5 1.4
#> 2 4.9 3.0 1.4
#> 3 4.7 3.2 1.3
#> 4 4.6 3.1 1.5
#> 5 5.0 3.6 1.4
#> 6 5.4 3.9 1.7

Created on 2022-09-26 with reprex v2.0.2

CodePudding user response:

If you are looking for a super simple method, this is also an option, though its probably less favorable compared to the other answers here if you have a lot of variables that need changing:

#### Load Library ####
library(tidyverse)

#### Emulate Data ####
df <- read.table(text = "             x           y            z
1          5.1         3.5          1.4
2          4.9         3.0          1.4
3          4.7         3.2          1.3
4          4.6         3.1          1.5
5          5.0         3.6          1.4
6          5.4         3.9          1.7", header = TRUE)

#### Rename Variables ####
df %>% 
  rename(X_1 = x,
         Y_2 = y,
         Z_3 = z)

Which gives you this:

  X_1 Y_2 Z_3
1 5.1 3.5 1.4
2 4.9 3.0 1.4
3 4.7 3.2 1.3
4 4.6 3.1 1.5
5 5.0 3.6 1.4
6 5.4 3.9 1.7
  •  Tags:  
  • r
  • Related