rook1996
rook1996

Reputation: 247

R:Dividing each element of a list with elements of another list

Assume I've one list with three vectors and another list containing three elements:

foo_list <- list(vector1=rnorm(10), vector2= rnorm(10), vector3=rnorm(10))
foo_list2 <- list(value1= 2, value2=4, value3=10)

Now I want that all 10 numbers of the element of vector1 should be divided by value1 (2), all 10 numbers of the element vector2 should be divided by value2(4) and so on.

This is just a short example. My real lists contains 20 vectors and 20 numbers. My main calculation is to calculate the percentage changes.

I tried mapply, but it gives the wrong results:

percentage_change <- function(data, actual) {
  ((data / actual) - 1) * 100
}
foo_results <- mapply(percentage_change, foo_list, foo_list2)

Upvotes: 0

Views: 3677

Answers (2)

Relasta
Relasta

Reputation: 1106

In a tidyverse way you can use purr::map2 and the following will do what you want

library(tidyverse)

results <- purrr::map2(foo_list, foo_list2, ~ .x / .y)

Iterating through the elements of foo_list and foo_list2 concurrently

Upvotes: 0

Gregor Thomas
Gregor Thomas

Reputation: 145785

Here's how to use mapply:

result = mapply(FUN = `/`, foo_list, foo_list2, SIMPLIFY = FALSE)

Though, I get the same results if I fix the syntax in your code:

# replaced final `)` with `}`, changed "value" to "actual" in the body
percentage_change <- function(data, actual) {
    ((data / actual) - 1) * 100
}

foo_results <- mapply(percentage_change, foo_list, foo_list2)
result_simple = (mapply(FUN = `/`, foo_list, foo_list2) - 1) * 100
all(foo_results == result_simple)
# [1] TRUE

So maybe your code is working and you got the right results? Or maybe it was just the bad function definition?

Upvotes: 1

Related Questions