Reputation: 161
I would like to multiply the numeric values two levels deep in a list by the values one level deep in another list in R. For example, consider the following:
library(tidyverse)
library(purrr)
library(dplyr)
weights <- list(a = list(1, 3, 8), b = list(2, 4), c = list(5, 2, 8, 0.5))
multiplier <- list(0.5, 0.25, 0.10)
This is the basic idea of what I'd like to do, but this does not work.....
result <- weights * multiplier
I would like to produce a list of lists with the same structure as the list titled "weights" but with each variable multiplied by the value in the "multiplier" list.
My desired result is:
result <- list(a = list(0.5, 1.5, 4), b = list(0.5, 1), c = list(0.5, 0.2, 0.8, 0.05))
I feel like this should be a relatively easy thing to do, but I can't seem to figure it out.
Upvotes: 1
Views: 290
Reputation: 887148
We can use map2
to loop over the list
, and as 'weights' is a nested list, unlist
it, multiply with each corresponding element from 'multiplier' list, and relist
it back to list
library(purrr)
map2(weights, multiplier, ~ relist(unlist(.x) * .y, skeleton = .x))
The similar option in base R
is with Map
Map(function(x, y) relist(unlist(x) * y, skeleton = x), weights, multiplier)
Or another option is to stack
it to a two column data.frame, and then do the multiplication after rep
licating to make lengths same and then relist
relist(with(stack(weights), values *
rep(unlist(multiplier), table(ind))), weights)
Upvotes: 1