我希望这不是一个重复的问题,因为我找不到我感兴趣的答案。我有 70 列,我想重命名它们。例如,我知道几种方法:
df1<-setmames (df1, c("BA1", "MA2", "NA3"...), c( "AB1","QB2","Q3"...))
但是这些方法没有帮助,因为我们有一个非常大的脚本。我想知道我们是否可以通过使用 tidyverse
的小脚本来做到这一点?
举个例子,假设我有这个表,我可以显示三列:
AB1 AB2 AB3
12 13 13
12 13 13
12 11 13
12 13 17
12 13 16
我要得到这张表
MZ1 MZ2 MZ3
12 13 13
12 13 13
12 11 13
12 13 17
12 13 16
考虑到这只是一个例子,我有 70 列。
最佳答案
我们可以使用索引或列名
names(df1)[1:70] <- v1
在哪里
v1<- c("AB1", "QB2", ...)
有了dplyr
,我们可以使用rename_at
library(dplyr)
library(stringr)
df1 <- df1 %>%
rename_at(1:70, ~ v1)
如果我们重命名以“AB”开头的列
names(df1)
#[1] "x1" "x2" "AB1" "AB2"
df1 %>%
rename_at(vars(matches('^AB\\d+$')), ~ str_replace(., 'AB', 'MZ'))
# x1 x2 MZ1 MZ2
#1 1 6 -0.5458808 0.6048889
#2 2 7 0.5365853 0.3707349
#3 3 8 0.4196231 0.6716903
#4 4 9 -0.5836272 0.6729823
#5 5 10 0.8474600 0.3204306
或者在base R
i1 <- grep("^AB\\d+$", names(df1))
names(df1)[i1] <- sub("AB", "MZ", names(df1)[i1])
更新
df2 <- df2 %>%
rename_at(vars(matches("^AB\\d+$")), ~ str_replace(., "AB", "MZ"))
df2
# MZ1 MZ2 MZ3
#1 12 13 13
#2 12 13 13
#3 12 11 13
#4 12 13 17
#5 12 13 16
数据
set.seed(24)
df1 <- data.frame(x1 = 1:5, x2 = 6:10, AB1 = rnorm(5), AB2 = runif(5))
原始数据值
df1
# x1 x2 AB1 AB2
#1 1 6 -0.5458808 0.6048889
#2 2 7 0.5365853 0.3707349
#3 3 8 0.4196231 0.6716903
#4 4 9 -0.5836272 0.6729823
#5 5 10 0.8474600 0.3204306
来自 OP 帖子的更新数据
df2 <- structure(list(AB1 = c(12L, 12L, 12L, 12L, 12L), AB2 = c(13L,
13L, 11L, 13L, 13L), AB3 = c(13L, 13L, 13L, 17L, 16L)),
class = "data.frame", row.names = c(NA, -5L))
关于重命名 R 中的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60327398/