Home > Net >  Replace the column indices in a list with column names
Replace the column indices in a list with column names

Time:11-06

I have a list indices_list in which I have the column indices of iris dataset. I want to replace the column indices with column names.

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

The expected outcome for indices_list_1 is -

1:  Sepal.Length  Petal.Length  Petal.Width  Petal.Length
2:  Sepal.Width  Sepal.Length  Sepal.Length  Sepal.Width

The expected outcome for 2nd scenario is -

$`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

CodePudding user response:

You may use column names of iris dataset as vector and the values in indices_list as index to subset.

library(data.table)
cols <- names(iris)
indices_list_1[, lapply(.SD, function(x) cols[x])]

#             V1           V2           V3           V4
#1: Sepal.Length Petal.Length  Petal.Width Petal.Length
#2:  Sepal.Width Sepal.Length Sepal.Length  Sepal.Width

For indices_list_2 this can be solved using lapply as -

out <- lapply(indices_list_2, function(x) {x[] <- cols[x];x})
names(out) <- cols[as.integer(names(out))]
out

#$Sepal.Length
#     [,1]           [,2]          
#[1,] "Sepal.Length" "Petal.Length"
#[2,] "Sepal.Width"  "Petal.Width" 

#$Petal.Length
#     [,1]           [,2]         
#[1,] "Petal.Length" "Sepal.Width"
#[2,] "Petal.Width"  "Sepal.Width"
  • Related