[英]R - Incrementing variable by grouping variables, based on changing column conditions
[英]grouping by column variables and appending a new variable based on condition
說我有一個數據框-
A列 | B列 |
---|---|
id1 | 藍色的 |
id1 | 紅色的 |
id1 | 灰色的 |
id2 | 紅色的 |
id3 | 紅色的 |
id3 | 灰色的 |
我想要這個輸出-
A列 | B列 |
---|---|
id1 | 全.混合 |
id2 | 紅色的 |
id3 | 紅.灰 |
我試過這個table1 <- mydf %>% group_by(ColA, ColB) %>% count(ColB)
並來到這個-
ColA ColB n
<chr> <chr> <int>
1 id1 blue 1
2 id1 red 1
3 id1 grey 1
4 id2 red 1
5 id3 red 1
6 id3 grey1 1
但在這之后我有點迷路了。 我想到了 group_by 並總結了 colB 中的行,但是如果我遇到這樣的情況 -
A列 | B列 |
---|---|
id5 | 灰色的 |
id5 | 灰色的 |
那我怎么辦?
目前尚不清楚您如何確定 output 中 B 列的值(例如“all.mixed”),但我們假設有一個calcMagicValue
function。一般流程如下所示:
calcMagicValue <- function(vals){
# psuedo code
if(all(possibleVals %in% vals)){
"all.mixed"
} else if( hasRedAndGrey){
"red.grey"
} else if(onlyRed) {
"red"
} else {
#...other conditions...
}
}
myDf |>
group_by(ColA) |>
summarize(newColB = calcMagicValue(ColB))
分組后,summarize 將遍歷分組列中的唯一值,並將匹配的行傳遞給調用的函數(在本例中calcMagicValue
)。 在這種情況下,您的結果將為分組列中的每個唯一組合/值占一行。
使用group_by
+ summarise
的方法略有不同,它使用一個指標在一個額外的mutate
步驟中替換all.mixed
案例:
library(dplyr)
dat %>%
group_by(Column.A) |>
summarise(all.mixed = all(unique(dat$Column.B) %in% Column.B),
Column.B = paste(Column.B, collapse = "."), .groups = "drop") |>
mutate(Column.B = if_else(all.mixed, "all.mixed", Column.B)) |>
select(-all.mixed)
#> # A tibble: 3 × 2
#> Column.A Column.B
#> <chr> <chr>
#> 1 id1 all.mixed
#> 2 id2 red
#> 3 id3 red.grey
數據
dat <- data.frame(
Column.A = c("id1", "id1", "id1", "id2", "id3", "id3"),
Column.B = c("blue", "red", "grey", "red", "red", "grey")
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.