Purrr: Referencing elements in 3D data structures for use in map and modify

After trawling SO and R bloggers for a few days, I have reverted to the R Studio Community for help in understanding referencing variables in 3D type structures (list columns list of dataframes) as they relate to the brilliant map and modify family of functions from Purrr.

The R users will be using these types of structures on a regular basis and need to be able to vectorize given the size of datasets and interactions with multiple server based databases.

So to my question which is in two parts:
How does a user reference the Nth element in a list column (1) or list of tables (2) and apply functions to update the value stored in the Nth element?

My apologies if my convention below is not standard - this is my first post!

To illustrate my example I have some simplified sample code below, which I hope someone will be able to demonstrate the referencing needed.

(1) what is the correct referencing from the below to update each of the values stored at l_var3 in each of the lists held in the list_column of the data frame commented at point (1) there is also a second example where values from other elements in each list are used as inputs to the product function also to update the values at l_var3

(2) is the same as (1) except being applied to a list of tables

# Example to show referencing in listcolumns or nested dataframes using Purrr
library(tidyverse)

# Create sample tibble
item_id <- seq(2,5)
const <- rep(24,4)
tbl_var1 <- seq(4,7)
tbl_var2 <- "Test"
tbl_var3 <-  rep(23,4)
tbl_var4 <- rep(22,4)
tib <- tibble(item_id,const,tbl_var1,tbl_var2,tbl_var3,tbl_var4)

# Create nested table column
tib <- tib %>% 
    group_by(item_id,const) %>% 
    nest(.key = "list_table")

# Create list column
list_c <- list(
  l_var1 = 4,
  l_var2 = "Test",
  l_var3 =  5,
  l_var4 = 6
)
tib$list_column <- list(list_c)

# Functions
update_fun <- function(a, b) { 
  a <- b 
  return(a)
  }

products_fun <- function(a, b, c) {
  a <- a*b*c
  return(a)
}

# (1) Using map and modify family on a list column: ?????

# Update every nth element in a list column with a value from a vector
# Update 3rd element l_var3 with const variable in tib
tib$list_column %>%   
  modify_depth(.[["l_var3"]],depth = 1, ~ update_fun(.x,tib$const))

# Update every nth element in a list column with a calculated value from multiple vectors
# Update 3rd element tbl_var3 with const variable in tib
tib$list_column %>%   
  modify_depth(.[["l_var3"]],depth = 1, ~ products_fun(.[["l_var3"]],.[["l_var4"]] ,.[["l_var1"]] ))

# (2) Using map and modify family on a nested table column:?????              
tib$list_table %>%  

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.