简体   繁体   English

如何基于R中的某些条件和总和对多行进行分组?

[英]How to group multiple rows based on some criteria and sum values in R?


数据快照


Hi All, Example :- The above is the data I have. 大家好,示例:-以上是我的数据。 I want to group age 1-2 and count the values. 我想对1-2岁年龄段进行分组并计算值。 In this data value is 4 for age group 1-2. 在此数据中,年龄组1-2的值为4。 Similarly I want to group age 3-4 and count the values. 同样,我想将3-4岁年龄段分组并计算值。 Here the value for age group 3-4 is 6. 此处3-4岁年龄段的值为6。

How can I group age and aggregate the values correspond to it? 如何对年龄进行分组并汇总与之对应的值?

I know this way: code- 我这样知道:代码-

data.frame(df %>% group_by(df$Age) %>% tally())

But the values are aggregating on individual Age. 但是这些值是在各个年龄段汇总的。 I want the values aggregating on multiple age to be a group as mentioned above example. 我希望在多个年龄段汇总的值成为上述示例中的一组。

Any help on this will be greatly helpful. 在这方面的任何帮助将大有帮助。 Thanks a lot to All. 非常感谢所有人。

Here's one way using dplyr and ?cut from base R - 这是使用dplyr?cut R从基数R-

df <- data.frame(age = c(1,1,2,2,3,3,3,4,4,4),
                 Name = letters[1:10],
                 stringsAsFactors = F)

df %>% 
  count(grp = cut(age, breaks = c(0,2,4)))

# A tibble: 2 x 2
  grp       n
  <fct> <int>
1 (0,2]     4
2 (2,4]     6

Here are two solutions, with base R and with package dplyr . 这是两个解决方案,分别是base R和dplyr软件包。
I will use the data posted by Shree . 我将使用Shree发布的数据。

First , base R. 首先 ,以R为基数。
I create a grouping variable grp and then aggregate on it. 我创建一个分组变量grp ,然后对其进行aggregate

grp <- with(df, c((age %in% 1:2) + 2*(age %in% 3:4)))
aggregate(age ~ grp, df, length)
#  grp age
#1   1   4
#2   2   6

Second a dplyr way. 第二dplyr方式。
Function case_when is used to create a grouping variable. 函数case_when用于创建分组变量。 This allows for meaningful names to be given to the groups in an easy way. 这允许以简单的方式为组赋予有意义的名称。

library(dplyr)

df %>%
  mutate(grp = case_when(
    age %in% 1:2 ~ "2:3",
    age %in% 3:4 ~ "3:4",
    TRUE ~ NA_character_
  )) %>%
  group_by(grp) %>%
  tally()
## A tibble: 2 x 2
#  grp       n
#  <chr> <int>
#1 1:2       4
#2 3:4       6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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