Retrieving the name of data frame to use as a prefix in column name

Viewed 45

This is a very small portion of my data:

A1 <- data.frame(Cell_ID = c("M", "M", "M", "BR", "BR", "BR"), 
                 Pulse_ID = c(1, 2, 3, 1, 2, 3),  
                 x = c(45.0495, 40.044, 55.0605, 45.0495, 40.044, 35.0385)) 
A2 <- data.frame(Cell_ID = c("M", "M", "M", "BR", "BR", "BR"), 
                 Pulse_ID = c(1, 2, 3, 1, 2, 3),  
                 x = c(30.033, 45.0495, 45.0495, 45.0495, 35.0385, 45.0495))

>A1     #A2 is the same format
  Cell_ID  Pulse_ID       x
     M         1       45.0495
     M         2       40.0440
     M         3       55.0605
    BR         1       45.0495
    BR         2       40.0440
    BR         3       35.0385

wells <- list(A1, A2) 

Pivoting the table so that each column is a new Cell_ID is fine. But I can't seem to insert the dataframe name as a prefix (e.g. names_prefix = "A1_") within the function below.

df <- lapply(wells, function(well){
  well %>%  
  pivot_wider(names_from = Cell_ID, values_from = x, names_prefix = **WHAT DO I INSERT HERE**) 
})
final <- df %>% reduce(full_join, by = "Pulse_ID")

I don't think I can run the dataframe through lapply while simultaneously trying to extract the dataframe name within the function. I considered using a loop but I can't figure that out either. I have over 100 dataframes to run this through so I can't enter each prefix manually. Ultimately, I need to combine the dataframes so the column names are very important.

My final product needs to look like this:

# A tibble: 6 x 9
  Pulse_ID  A1_M A1_BR  A2_M A2_BR  A3_M... 
     1      45.0  45.0  30.0  55.1  ...   and so on
     2      40.0  40.0  45.0  45.0  ...   
     3      55.1  35.0  45.0  30.0  ...   

Any suggestions? Thanks!

2 Answers

You can create a named list with lst function join them in one dataframe using id column and get the data in wide format.

library(tidyverse)

lst(A1, A2)  %>%
  bind_rows(.id = 'id') %>%
  pivot_wider(names_from = c(id, Cell_ID), values_from = x)

#  Pulse_ID  A1_M A1_BR  A2_M A2_BR
#     <dbl> <dbl> <dbl> <dbl> <dbl>
#1        1  45.0  45.0  30.0  45.0
#2        2  40.0  40.0  45.0  35.0
#3        3  55.1  35.0  45.0  45.0

You could create a named list:

wells <- list(A1 = A1, A2 = A2) 

And then with the addition of purrr, you could do:

imap(wells,
     ~ .x %>%  
         pivot_wider(names_from = Cell_ID, 
                     values_from = x, 
                     names_prefix = paste0(.y, "_"))) %>% 
    reduce(full_join, by = "Pulse_ID")

  Pulse_ID  A1_M A1_BR  A2_M A2_BR
     <dbl> <dbl> <dbl> <dbl> <dbl>
1        1  45.0  45.0  30.0  45.0
2        2  40.0  40.0  45.0  35.0
3        3  55.1  35.0  45.0  45.0
Related