繁体   English   中英

R tidyverse 操纵 dataframe

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM