我目前有這張表,我想總結每個 ID 的購買總數。
輸入:
| ID | 購買 | 時間 |
|---|---|---|
| 一個 | 需要 | 1:00 |
| 一個 | 想 | 1:30 |
| 一個 | 沒有任何 | 2:00 |
| b | 需要 | 1:15 |
| b | 想 | 1:30 |
| C | 沒有任何 | 1:10 |
| C | 沒有任何 | 1:30 |
| d | 沒有任何 | 2:00 |
| d | 需要 | 2:10 |
| d | 想 | 2:15 |
| d | 沒有任何 | 2:35 |
| e | 沒有任何 | 3:10 |
| e | 沒有任何 | 3:50 |
| F | 需要 | 2:55 |
| F | 想 | 3:15 |
| F | 需要 | 3:20 |
購買欄主要是不存在的,而是有專案名稱。所以我先創建了這個專欄,然后繼續嘗試達到下面的輸出
期望的第一次輸出:購買的物品總數,需要和想要的數量,如果第一次購買是需要的,輸出列是,如果不是,沒有,如果沒有購買
| ID | 全部的 | 需要 | 想 | 輸出 |
|---|---|---|---|---|
| 一個 | 2 | 1 | 1 | 是的 |
| b | 2 | 1 | 1 | 是的 |
| C | 0 | 0 | 0 | 沒有任何 |
| d | 2 | 1 | 1 | 不 |
| e | 0 | 0 | 0 | 沒有任何 |
| F | 3 | 2 | 1 | 是的 |
我正在使用 dplyr,所以我很感激建議的代碼對于添加到 dplyr 管道是可行的。
我試圖做的
actions %>% group_by (id) %>% arrange(id) %>%
mutate(purchases = ifelse(type == "Buy" & obj_category == "Books" | type == "Buy" & obj_category == "Car" | type=="Buy" & obj_category == "Business" | type == "Buy", "need",
ifelse(type == "Buy" & obj_category == "Sweets" | type == "Buy" & obj_category == "Electronics" | type == "Buy" & obj_category == "Business" | type == "Buy" & obj_category == "House", "want", "none"))) %>%
summarise(need = ifelse(purchases == "need", 1, 0),
want = ifelse(purchases == "want", 1, 0))
先感謝您
uj5u.com熱心網友回復:
你可以試試
library(dplyr)
df %>%
group_by(id) %>%
summarise(need = sum(purchases == "need"),
want = sum(purchases == "want"),
total = need want,
output = case_when(first(purchases) == "need" ~ "yes",
total == 0 ~ "none",
TRUE ~ "no"))
# # A tibble: 6 × 5
# id need want total output
# <chr> <int> <int> <int> <chr>
# 1 a 1 1 2 yes
# 2 b 1 1 2 yes
# 3 c 0 0 0 none
# 4 d 1 1 2 no
# 5 e 0 0 0 none
# 6 f 2 1 3 yes
如果有更多類別,則為通用版本purchases:
library(dplyr)
library(janitor)
df %>%
tabyl(id, purchases) %>%
select(-none) %>%
adorn_totals("col") %>%
left_join(
df %>% group_by(id) %>%
summarise(output = case_when(purchases[1] == "need" ~ "yes",
all(purchases == "none") ~ "none",
TRUE ~ "no")))
資料
df <- structure(list(id = c("a", "a", "a", "b", "b", "c", "c", "d",
"d", "d", "d", "e", "e", "f", "f", "f"), purchases = c("need",
"want", "none", "need", "want", "none", "none", "none", "need",
"want", "none", "none", "none", "need", "want", "need"), time = c("1:00",
"1:30", "2:00", "1:15", "1:30", "1:10", "1:30", "2:00", "2:10",
"2:15", "2:35", "3:10", "3:50", "2:55", "3:15", "3:20")), class = "data.frame", row.names = c(NA, -16L))
uj5u.com熱心網友回復:
這是一個使用dplyrand的解決方案janitor:
library(dplyr)
library(janitor)
df %>%
janitor::tabyl(id, purchases) %>%
left_join(df %>% group_by(id) %>% slice(1), by = "id") %>%
rowwise() %>%
mutate(total = sum(c_across(need:want))) %>%
ungroup() %>%
mutate(purchases = ifelse(purchases == "need", "yes", "no"),
purchases = ifelse(total == 0, "none", purchases)) %>%
select(-c(time, total))
這使:
# A tibble: 6 × 5
id need none want purchases
<chr> <dbl> <dbl> <dbl> <chr>
1 a 1 1 1 yes
2 b 1 0 1 yes
3 c 0 2 0 no
4 d 1 2 1 no
5 e 0 2 0 no
6 f 2 0 1 yes
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/488575.html
