问题
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!
回答1:
In base R you can use Map
.
Example 1
z <- c(10, 50, 6, 12)
Map(function(v, w) { v$x <- replace(v$x, 3, w); v; }, test_list, z)
#[[1]]
#[[1]]$x
#[1] 10 101 10
#
#[[1]]$y
#[1] 9 12 11
#
#
#[[2]]
#[[2]]$x
#[1] 10 133 50
#
#[[2]]$y
#[1] 9 15 13
#
#
#[[3]]
#[[3]]$x
#[1] 10 101 6
#
#[[3]]$y
#[1] 9 18 11
#
#
#[[4]]
#[[4]]$x
#[1] 10 101 12
#
#[[4]]$y
#[1] 9 10 15
Example 2
Map(function(v, w) { v$x <- replace(v$x, 3, w); v; }, test_list, rnorm(length(test_list)))
Or the same using purrr::map2
purrr::map2(test_list, z, function(v, w) { v$x <- replace(v$x, 3, w); v; })
purrr::map2(test_list, rnorm(length(test_list)), function(v, w) { v$x <- replace(v$x, 3, w); v; })
来源:https://stackoverflow.com/questions/51604391/modifying-specified-list-elements-r