Tom
Tom

Reputation: 57

How to access the name of a data frames within a list using lapply

library(data.table)

dt <- data.table(V1 = c("Name1", "Name2", "Name3"),  
                 V2 = c(1,2,3),  
                 V3 = c(1,2,3)  
                 )

For reproducibility I've defined the names of the list elements above, but in my data I do not have a list of the datatable names.

I turn the datatable into a list using split:

List <- split(dt, with(dt, interaction(V1)), drop = TRUE)

List
$Name1
      V1 V2 V3
1: Name1  1  1

$Name2
      V1 V2 V3
1: Name2  2  2

$Name3
      V1 V2 V3
1: Name3  3  3

I'm using lapply to manipulate the elements in the list and as part of this I want to access the names of those datatables. names() gives me the variable names of the datatables. How do I reference the names of the datatables?

Listnames <- lapply(List, function(x) {
  names(x)
})

Listnames 
$Name1
[1] "V1" "V2" "V3"

$Name2
[1] "V1" "V2" "V3"

$Name3
[1] "V1" "V2" "V3"

Upvotes: 0

Views: 38

Answers (2)

Sirius
Sirius

Reputation: 5429

purrr's imap was (among other things) invented for this:


library(purrr)

foo <- List %>% imap( function(x,y) {
             cat( "x = ", toString(x), "\n" )
             cat( "y = ", toString(y), "\n" )
         })

Output:

x =  Name1, 1, 1 
y =  Name1 
x =  Name2, 2, 2 
y =  Name2 
x =  Name3, 3, 3 
y =  Name3 

x is the data, y is the name in each iteration

Upvotes: 1

AnilGoyal
AnilGoyal

Reputation: 26218

Do you want this?

lapply(seq_along(List), FUN = function(x) names(List)[x])

[[1]]
[1] "Name1"

[[2]]
[1] "Name2"

[[3]]
[1] "Name3"

Upvotes: 1

Related Questions