[SOLVED] Converting the names of a list elements as a variable in a data.frame

Issue

I have a named List of data.frames. I was wondering how to convert the name ("bar1",…,"bar4") of each element List as a column next to each data.frame?

My final desired_output is shown below.

List <- list(bar1=data.frame(study="A",sd = 1), bar2=data.frame(study=c("B","C"),sd=2:3),
     bar3=data.frame(study="Z",sd = 4), bar4=data.frame(study="H",sd=5))

# desired_output:
"
  study sd   id
      A  1 bar1
      B  2 bar2
      C  3 bar2
      Z  4 bar3
      H  5 bar4
"

Solution

When I think of iterating over a vector I think of the map functions in purrr. In this case, map2() iterates over multiple arguments simultaneously. I grabbed the names of the list elements and stored them in a vector, n:

n <- names(List)

I then iterated over List and n at the same time, calling cbind() to add a variable (i.e., column) to each data frame:

map2(List, n, ~ cbind(.x, Name = .y))

Output:


$bar1
study sd Name
1 A 1 bar1

$bar2
study sd Name
1 B 2 bar2
2 C 3 bar2

$bar3
study sd Name
1 Z 4 bar3

$bar4
study sd Name
1 H 5 bar4

We can collapse List to a single data frame with a call to bind_rows():

result <- map2(List, n, ~ cbind(.x, Name = .y))
bind_rows(result)

Output:


study sd Name
1 A 1 bar1
2 B 2 bar2
3 C 3 bar2
4 Z 4 bar3
5 H 5 bar4

Taken as one statement that would be:

map2(List, names(List), ~ cbind(.x, Name = .y)) %>% 
  bind_rows()

Answered By – rdelrossi

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.