[英]R tidyverse manipulating dataframe
數據:
name_id name_desc is_mand count
howard101 howards id 1 123
howard101 howards id 0 4
rando12 random pers 1 500
peter54 peters name 1 10
peter54 peters name 0 14
danny66 dannys acc 0 20
我有如上所示的數據,name_id 可以是強制性的(1)或不是(0)。 如果 name_id 有一個強制性和非強制性列,我想對計數求和,而 label 它是強制性的(is_mand = 1)。 我怎樣才能做到這一點?
預期 output:
name_id name_desc is_mand count
howard101 howards id 1 127
rando12 random pers 1 500
peter54 peters name 1 24
danny66 dannys acc 0 20
我有如圖所示的數據
我想我可以按 name_id 分組,當計數大於 2 時,只需 label 將其作為強制性並求和?
您是否嘗試根據每個 name_id 的強制和非強制值來匯總計數?
如果是這樣,您將使用匯總 function:
df_summary <- df %>% group_by(name_id, name_description, is_mand) %>% summarise(count = sum(name_id, na.rm = TRUE)
或者,如果您只想按 is_mand 過濾,您可以使用:
df_filtered <- df[df$is_mand == 1,]
您還可以將這兩個操作與過濾器 function 結合起來:
df_summary <- df %>% group_by(name_id, name_description, is_mand) %>% summarise(count = sum(name_id, na.rm = TRUE) %>% filter(is_mand == 1)
這大致是你要求的嗎?
這是通過 dplyr 中的group_by()
和summarise()
完成的dplyr:
df %>%
group_by(name_id, name_desc) %>%
summarise(is_mand = sum(is_mand),
count = sum(count))
name_id name_desc is_mand count
<chr> <chr> <dbl> <dbl>
1 danny66 dannys acc 0 20
2 howard101 howards id 1 127
3 peter54 peters name 1 24
4 rando12 random pers 1 500
另一個使用ifelse()
語句匹配name_id
的選項,其中任何is_mand
等於 1。
df %>%
group_by(name_id, name_desc) %>%
summarize(is_mand = ifelse(any(is_mand == 1), 1, 0),
count = ifelse(any(is_mand == 1), sum(count), count))
數據
df <- structure(list(name_id = c("howard101", "howard101", "rando12",
"peter54", "peter54", "danny66"), name_desc = c("howards id",
"howards id", "random pers", "peters name", "peters name", "dannys acc"
), is_mand = c(1, 0, 1, 1, 0, 0), count = c(123, 4, 500, 10,
14, 20)), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.