I have an output that looks like this:
test_list <- list(list(x = c(10, 101, 3), y = c(9, 12, 11)),
list(x = c(10, 133, 4), y = c(9, 15, 13)),
list(x = c(10, 101, 90), y = c(9, 18, 11)),
list(x = c(10, 101, 1), y = c(9, 10, 15)))
I would like to select and modify specific elements of sublists x and y. For example I would like to replace the last element of x with a number from a vector or generated from a function - i.e; map the vector z <- c(10, 50, 6, 12) over the last element of sublists x to result in:
test_list_1 <- list(list(x = c(10, 101, 10), y = c(9, 12, 11)),
list(x = c(10, 133, 50), y = c(9, 15, 13)),
list(x = c(10, 101, 6), y = c(9, 18, 11)),
list(x = c(10, 101, 12), y = c(9, 10, 15)))
or a function such as rnorm(1) over the last element of each sublist x to result in the output from:
test_list_2 <- list(list(x = c(10, 101, rnorm(1)), y = c(9, 12, 11)),
list(x = c(10, 133, rnorm(1)), y = c(9, 15, 13)),
list(x = c(10, 101, rnorm(1)), y = c(9, 18, 11)),
list(x = c(10, 101, rnorm(1)), y = c(9, 10, 15)))
I have been trying the purrr package but the syntax are new to me.
Attempted:
purrr::map(test_list, ~ .x$x[length(.x$x)]) selects correct list/depth but unable to modify.
purrr::modify_depth(test_list, 2, rnorm(1)) I can see why this selects the incorrect depth but not sure how to correct.
So far I can only find examples of manipulating simple list structures in simple ways or complex examples I have not managed to transfer.
Any help would be much appreciated, overall my attempts seem quite clumsy and difficult to generalise for future use.
Thanks!