Here is my list of vectors.
j = list(x = c('apple', 'avocado'), y = c('banana', 'beetroot'))
Here are the contents of j.
$x
[1] "apple" "avocado"
$y
[1] "banana" "beetroot"
Here is the desired output.
$x
[1] "x_apple" "x_avocado"
$y
[1] "y_banana" "y_beetroot"
CodePudding user response:
You can use purrr::imap()
:
library(purrr)
imap(j, ~ paste0(.y, "_", .x))
Output
$x
[1] "x_apple" "x_avocado"
$y
[1] "y_banana" "y_beetroot"
The "i" in imap()
means index, and conveniently lets you pass both the elements of a vector and its names into a function.
CodePudding user response:
In base R, you can use Map
-
Map(function(x, y) paste(x, y, sep = '_'), names(j), j)
#$x
#[1] "x_apple" "x_avocado"
#$y
#[1] "y_banana" "y_beetroot"