Home > Back-end >  Using the purrr::map() function in R to apply a statistical test to a list
Using the purrr::map() function in R to apply a statistical test to a list

Time:01-25

I have a data frame with closing prices of the 30 DOW stock indices for the past 10 years. I want to apply some statistical tests to each stock in the data frame. I want to use the map function from the purrr package. That's what I do:

#First I split my data frame aggregating the closing prices for 30 different stocks 
#into a list combining 30 different data frames, one for each stock. 
#Each data frame has only three variables - date, closing price and stock symbol.

DOW_list <- DOW_prices_df %>%
            split(.$stock_symbol)

#Then I use the map function to apply the Cox Stuart Statistical Test to the closing prices
#of each stock in the list
map(DOW_list, cox.stuart.test($closing_price)) 

However, this doesn't work. I get the following error:

Error in stopifnot(is.numeric(x)) : 
  argument "x" is missing, with no default

My goal is to get the results of the statistical test for each of the 30 stocks. Can someone please explain what I am doing wrong? I will greatly appreciate your time and help!

EDIT: Thank you so much for your help! The original question is resolved. I have a follow-up question. Is there a way in which I can transform the outputs of my statistical tests into a data frame? So that I have two variables in such a data frame, the stock symbol and the p-value of the statistical test.

CodePudding user response:

With map, we need a lambda (~) function,

library(purrr)
map(DOW_list, ~ cox.stuart.test(.x$closing_price))

CodePudding user response:

If you have a list of data frames you could use the anonymous function notation with lapply or map like this using mtcars as an example:

cars <- split(mtcars, mtcars$cyl)
lapply(cars, function(x) mean(x$mpg))
$`4`
[1] 26.66364

$`6`
[1] 19.74286

$`8`
[1] 15.1

map(cars, function(x) mean(x$mpg))
$`4`
[1] 26.66364

$`6`
[1] 19.74286

$`8`
[1] 15.1
  •  Tags:  
  • Related