簡體   English   中英

匯總值dplyr r

[英]Summarise values dplyr r

我有一個目標變量,范圍是-33到17,並且具有int類型的變量mercer_category_id。

summary(total_trans$target)
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
-33.21928  -0.80808  -0.09018  -0.45554   0.54223  17.96507 

str(total_trans$merchant_category_id)
merchant_category_id: int  278 307 705 307 705 307 705 307 278 332

我想僅當目標變量小於或等於第一個四分位數時,才從最小到最大查找變量商人_類別_id的數量。

我試圖這樣做:

total_trans %>% group_by(merchant_category_id) %>% summarise(counting = count(merchant_category_id))

響應是一個錯誤:

Error in summarise_impl(.data, dots) : 
  Evaluation error

后:

total_trans %>% summarise(Range = list(range(merchant_category_id[target <= summary(target)[2]])))

響應:

    Range
1 -1, 891

也可以嘗試:

total_trans %>% group_by(merchant_category_id) %>% summarise(Range = list(range(target[target < -0.80808])))

響應:

# A tibble: 325 x 2
   merchant_category_id Range    
                  <int> <list>   
 1                   -1 <dbl [2]>
 2                    2 <dbl [2]>
 3                    9 <dbl [2]>
 4                   11 <dbl [2]>
 5                   14 <dbl [2]>
 6                   16 <dbl [2]>
 7                   18 <dbl [2]>
 8                   19 <dbl [2]>
 9                   21 <dbl [2]>
10                   27 <dbl [2]>
# ... with 315 more rows
There were 26 warnings (use warnings() to see them)

如果我這樣做

total_trans %>% count(merchant_category_id, wt = target < -0.80808)

要么

total_trans %>%
  mutate(q1 = target <= quantile(target, 1/4)) %>%
  filter(q1) %>%
  group_by(merchant_category_id) %>%
  summarise(count = n())

我得到這個回應:

   merchant_category_id     n
                  <int> <int>
 1                   -1   432
 2                    2  8364
 3                    9  2580
 4                   11     9
 5                   14  1800
 6                   16   177
 7                   18     4
 8                   19 24371
 9                   21   466
10                   27     4

這幾乎是我所需要的。 只需要從最大數量到最小數量訂購列n

如何使用dplyr做到這一點?

我不知道這是最好的答案:

top_n(total_trans %>%
  mutate(q1 = target <= quantile(target, 1/4)) %>%
  filter(q1) %>%
  group_by(merchant_category_id) %>%
  summarise(count = n())%>% arrange(desc(count)), 20)

但是可以使用top_n。

非常感謝大家!!!!

對於我對這個問題的理解,類似以下的內容可以做到。

首先組成一個數據集。

set.seed(1234)
n <- 100
total_trans <- data.frame(merchant_category_id = sample.int(20, n, TRUE),
                          target = runif(n, -33, 17))

現在的問題。

library(dplyr)

total_trans %>%
  mutate(q1 = target <= quantile(target, 1/4)) %>%
  filter(q1) %>%
  group_by(merchant_category_id) %>%
  summarise(count = n())

注意,這兩個代碼行mutatefilter可以成為僅一個: filter(target <= quantile(target, 1/4)) 我這樣保留代碼,使其更具可讀性。

編輯。

以下內容按計數排序,僅保留結果的前20行。

total_trans %>%
  filter(target <= quantile(target, 1/4)) %>%
  count(merchant_category_id) %>%
  arrange(desc(n)) %>%
  head(20)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM