[英]How to add the position index as the suffix into the columns in R?
I just have a data.frame like this:我只有一个这样的data.frame:
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!谢谢!
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
:
paste(colnames(df), seq(ncol(df)), sep = "_")
Also works with seq_along
:也适用于
seq_along
:
paste(colnames(df), seq_along(df), sep = "_")
dplyr
approach using rename_with
like this: dplyr
方法使用rename_with
像这样:
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使用reprex v2.0.2创建于 2022-09-26
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.