用关联的字符串替换列名称的元素

问题描述 投票:0回答:1

我有一个带有自动生成的列名称的 data.table。名称采用以下形式:

N.x.y.z

其中 N 是一个字符(字面意思是 N),其余变量都是整数。

我还有一个 .csv,它将 x 的迭代与有意义的字符串相关联。如:

X 姓名
1 型号
3 里程

我想做的是按照以下格式重新生成列名称:

N.姓名.y.z

我尝试首先提取列名称,例如

thefile = fread('filepath')

xx <- colnames(thefile)

colindex <- read.csv('the other file path')
colindex[,1] <- paste0('N.', colindex[,1], '.') #Converting x to N.x.

我用 grepl、replace_at 搞乱了,用“.”分割字符串

r dataframe r-colnames
1个回答
0
投票
read.table(text = "X    Name
                   1    Model
                   3    Mileage", 
           header = T, stringsAsFactor = FALSE) -> colindex


df1 <- data.frame(`N.1.2.3` = c(1,2), `N.3.1.2` = c(6,5), 
                  `N.1.3.1` = c(3, 4), `N.3.2.2` = c(8, 7))

df1
#>   N.1.2.3 N.3.1.2 N.1.3.1 N.3.2.2
#> 1       1       6       3       8
#> 2       2       5       4       7

names_split <-  as.data.frame(strsplit(names(df1), "\\."))
names_split[2,] <-  colindex[match(names_split[2,], colindex$X), "Name"]
names(df1) <- apply(names_split, 2, paste, collapse = ".")

df1
#>   N.Model.2.3 N.Mileage.1.2 N.Model.3.1 N.Mileage.2.2
#> 1           1             6           3             8
#> 2           2             5           4             7

创建于 2024-03-18,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.