[英]Apply test (Jarque-Bera) to subgroups with map()
我正在嘗試對數據集的子組運行測試 (Jarque-Bera)。 我正在嘗試為此使用purrr
的函數map()
,但不知何故它對我來說失敗了。
對於此處的示例,我將使用內置的ChickWeight
數據集:
加載一些包:
library(dplyr)
library(ggplot2)
library(tidyr)
library(purrr)
library(tseries)
數據如下所示:
ggplot(ChickWeight, aes(weight, fill = Diet)) +
geom_histogram() +
facet_wrap(~Diet)
我現在正在嘗試對子組飲食 1、2、3 和 4 使用 Jarque-Bera 測試。
我知道如何在這樣的組之一上使用它:
ChickWeight %>%
filter(Diet == 1) %>%
pull(weight) %>%
jarque.bera.test()
返回:
Jarque Bera Test
data: .
X-squared = 46.687, df = 2, p-value = 7.278e-11
但是現在,我想為所有子組執行此操作。 所以我像這樣嵌套數據:
nst <- ChickWeight %>%
nest(-Diet)
現在我想我可以立即應用purrr
的map()
函數,但它是如何失敗的:
tsts <- nst %>%
map(jb = map(data, jarque.bera.test(weight)))
返回:
as_mapper(.f, ...) 中的錯誤:缺少參數“.f”,沒有默認值
我也試過:
tsts <- nst %>%
mutate(jb = map(data, jarque.bera.test(weight)))
這會產生:
mutate_impl(.data, dots) 中的錯誤:評估錯誤:未找到對象“權重”。
你的對象nst
是一個數據框; 在引擎蓋下,數據框是一個列列表。 因此,如果您將map
應用於nst
,它將映射列而不是映射數據中的組。 另外,請注意map
的第二個參數必須是一個函數(或一些其他類型的函數簡寫表達式——請參閱purrr::map
的文檔)。
有很多方法可以解決您的問題。 我最喜歡的是使用group_by
並從dplyr和tidy
從broom一起do
:
library(dplyr)
library(tidyr)
library(purrr)
library(tseries)
library(broom)
ChickWeight %>%
group_by(Diet) %>%
do(tidy(jarque.bera.test(.$weight)))
# # A tibble: 4 x 5
# # Groups: Diet [4]
# Diet statistic p.value parameter method
# <fct> <dbl> <dbl> <dbl> <fct>
# 1 1 46.7 7.28e-11 2 Jarque Bera Test
# 2 2 18.8 8.36e- 5 2 Jarque Bera Test
# 3 3 12.4 2.00e- 3 2 Jarque Bera Test
# 4 4 5.17 7.54e- 2 2 Jarque Bera Test
請注意, tidy
獲取jarque.bera.test
的輸出並將其轉換為一行數據框,並且do
函數對每個組重復此do
。 這是一個純dplyr方法:
ChickWeight %>%
group_by(Diet) %>%
summarize(p.value = jarque.bera.test(weight)$p.value)
# # A tibble: 4 x 2
# Diet p.value
# <fct> <dbl>
# 1 1 7.28e-11
# 2 2 8.36e- 5
# 3 3 2.00e- 3
# 4 4 7.54e- 2
接下來是一種使用nest
和map
。 請注意, nest
創建的數據框的第二列是一個列表列。 我們使用pull
只拉取列表列,然后使用map
對每個組執行 Jarque-Bera 測試。
ChickWeight %>%
nest(-Diet) %>%
pull(data) %>%
map(~ jarque.bera.test(.$weight))
# [[1]]
#
# Jarque Bera Test
#
# data: .$weight
# X-squared = 46.687, df = 2, p-value = 7.278e-11
#
#
# [[2]]
#
# Jarque Bera Test
#
# data: .$weight
# X-squared = 18.779, df = 2, p-value = 8.36e-05
#
#
# [[3]]
#
# Jarque Bera Test
#
# data: .$weight
# X-squared = 12.426, df = 2, p-value = 0.002003
#
#
# [[4]]
#
# Jarque Bera Test
#
# data: .$weight
# X-squared = 5.1686, df = 2, p-value = 0.07545
請注意, map 接受公式作為編寫匿名函數的緊湊方式。 最后,這里有一些比較笨拙的方法,它們結合了map
和dplyr :
map(1:4, ~ filter(ChickWeight, Diet == .) %>% pull(weight) %>% jarque.bera.test)
map(1:4, ~ filter(ChickWeight, Diet == .)) %>%
map(~ pull(., weight)) %>%
map(~ jarque.bera.test(.))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.