将列表中的iris数据集列索引替换为对应列名
问题描述
我有两个包含iris数据集列索引的对象:indices_list_1(data.table类型)和indices_list_2(嵌套列表类型),需要将其中的列索引替换为iris数据集对应的列名。具体对象定义如下:
data(iris) indices_list_1 = structure(list(V1 = c(1L, 2L), V2 = c(3L, 1L), V3 = c(4L, 1L), V4 = c(3L, 2L)), row.names = c(NA, -2L), class = c("data.table", "data.frame")) indices_list_2 = list(`1` = structure(c(1L, 2L, 3L, 4L), dim = c(2L, 2L)), `3` = structure(c(3L, 4L, 2L, 2L), dim = c(2L, 2L)))
原对象输出:
indices_list_1:
V1 V2 V3 V4 1: 1 3 4 3 2: 2 1 1 2
indices_list_2:
$`1` [,1] [,2] [1,] 1 3 [2,] 2 4 $`3` [,1] [,2] [1,] 3 2 [2,] 4 2
预期输出:
indices_list_1:
1: Sepal.Length Petal.Length Petal.Width Petal.Length 2: Sepal.Width Sepal.Length Sepal.Length Sepal.Width
indices_list_2:
$`Sepal.Length` [,1] [,2] [1,] Sepal.Length Petal.Length [2,] Sepal.Width Petal.Width $`Petal.Width` [,1] [,2] [1,] Petal.Length Sepal.Width [2,] Petal.Width Sepal.Width
解决方法
首先提取iris的列名作为索引-列名映射表:
col_names <- colnames(iris)
处理data.table对象indices_list_1
利用data.table的lapply(.SD, ...)遍历所有列,将每个元素替换为对应的列名:
indices_list_1 <- indices_list_1[, lapply(.SD, function(x) col_names[x])]
处理嵌套列表对象indices_list_2
分两步操作:先替换列表的名称,再替换每个矩阵内的索引值:
# 替换列表的名称 names(indices_list_2) <- col_names[as.integer(names(indices_list_2))] # 遍历每个矩阵,替换内部的索引 indices_list_2 <- lapply(indices_list_2, function(mat) { mat[] <- col_names[mat] mat })
运行上述代码后,即可得到预期的替换结果。
内容的提问来源于stack exchange,提问作者Saurabh
相关产品推荐
相关产品推荐

