[英]Using dplyr summarise with conditions
我目前正在嘗試應用摘要功能,以便從大型數據集中分離出相關的觀察結果。 這里給出一個簡單的可復制示例:
df <- data.frame(c(1,1,1,2,2,2,3,3,3), as.logical(c(TRUE,FALSE,TRUE,TRUE,TRUE,TRUE,FALSE,TRUE,FALSE)),
as.numeric(c(0,5,0,0,0,0,7,0,7)))
colnames(df) <- c("ID", "Status", "Price")
ID Status Price
1 1 TRUE 0
2 1 FALSE 5
3 1 TRUE 0
4 2 TRUE 0
5 2 TRUE 0
6 2 TRUE 0
7 3 FALSE 7
8 3 TRUE 0
9 3 FALSE 7
我想按觀察對表進行排序,並且僅當所有三個觀察都為真(變通)時才獲得狀態為真,然后要獲取與該狀態相對應的價格(即,對於觀察1為5表示假,對於觀察2為0表示假)。 TRUE,觀察值3為FALSE,為7)。
通過對dplyr中的條件進行匯總 ,我發現可以像往常一樣在方括號中指定條件。 到目前為止,我的代碼如下所示:
library(dplyr)
result <- df %>%
group_by(ID) %>%
summarize(Status = all(Status), Test = ifelse(all(Status) == TRUE,
first(Price[Status == TRUE]), first(Price[Status == FALSE])))
# This is what I get:
# A tibble: 3 x 3
ID Status Test
<dbl> <lgl> <dbl>
1 1. FALSE 0.
2 2. TRUE 0.
3 3. FALSE 7.
但是正如您所看到的,對於ID = 1,它給出了不正確的價格。 我一直在嘗試這種方法,因此,如果有任何提示,我將不勝感激。
能做:
df %>%
group_by(ID) %>%
mutate(status = Status) %>%
summarise(
Status = all(Status),
Test = ifelse(Status == TRUE,
first(Price),
first(Price[status == FALSE]))
)
輸出:
# A tibble: 3 x 3
ID Status Test
<dbl> <lgl> <dbl>
1 1 FALSE 5
2 2 TRUE 0
3 3 FALSE 7
問題是您要在已修改Status
列的情況下使用Status
Test
Status
”列,以使其不再包含原始值。
進行復制之前(我已將其保存為status
),對其執行ifelse
,它將正常運行。
我們可以保持all(Status)
在第二個參數summarise
(或更改列名),也,它是可以做到if/else
的邏輯似乎返回基於無論是單TRUE / FALSE all
“狀態的'是否為真
df %>%
group_by(ID) %>%
summarise( Test = if(all(Status)) first(Price[Status]) else
first(Price[!Status]), Status = all(Status))
# A tibble: 3 x 3
# ID Test Status
# <dbl> <dbl> <lgl>
#1 1 5 FALSE
#2 2 0 TRUE
#3 3 7 FALSE
注意:最好不要使用長度不相等的ifelse
作為參數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.