【问题标题】:Summarize data with condition and create new row (dplyr)使用条件汇总数据并创建新行 (dplyr)
【发布时间】:2017-12-03 14:45:51
【问题描述】:

我会尝试用一个例子来说明我的问题。

示例数据框:

myData <- data.frame(Country = c("Germany","UK","Mexico","Spain"),
                     MyCount = c(300,800,950,125),
                     Continent = c("Europe","Europe","America","Europe"))  

Country  MyCount Continent
Germany  300     Europe
UK       800     Europe
Mexico   950     America
Spain    125     Europe

预期结果:

Country MyCount Continent
Other   425     Europe
UK      800     Europe

我试过了。

myData %>%
  filter(Continent == "Europe" & MyCount < 800)%>%
  add_row(Country = "Other", MyCount = sum(MyCount), Continent = "Europe")  

【问题讨论】:

  • 请更清楚地说明您想做什么以及您正在努力解决什么问题?您是否只是想向 data.frame 添加一行?您是否尝试以某种特定方式汇总数据?
  • @jmuhlenkamp 是的,我需要从 sum myCount 创建新行,但只有 myCount

标签: r dplyr


【解决方案1】:

@Mandy 我对您的用例的具体要求不是很清楚,但这应该根据您的 cmets 工作。使用来自 dplyr 的 group_bysummarise

myData %>% 
       filter(Continent == 'Europe') %>% 
       mutate(grp = ifelse(MyCount < 800, 'Other', Country)) %>% 
       group_by(grp) %>% 
       summarise(MyCount = sum(MyCount))

# A tibble: 2 × 2
grp MyCount
<chr>   <dbl>
1 Other     425
2    UK     800

【讨论】:

  • 我会在 ifelse 语句中添加 as.character(Country),因为当我尝试您的代码时,它会在输出中显示“4”而不是 UK,就好像它已经变成了因子一样。
  • 是的,我认为这是因为 OP 如何为玩具问题设置 data.frame。如果没有,最好完全避免因素myData &lt;- data.frame(Country = c("Germany","UK","Mexico","Spain"), MyCount = c(300,800,950,125), Continent = c("Europe","Europe","America","Europe")), stringsAsFactors = FALSE
【解决方案2】:

不完全清楚您在寻找什么,但这会给您在问题中发布的结果。

library(dplyr)
myData<-data.frame(Country=c("Germany","UK","Mexico","Spain"),MyCount=c(300,800,950,125),Continent=c("Europe","Europe","America","Europe")) 

myData %>%
    filter(Continent == 'Europe') %>%
    mutate(Country = as.character(Country),
           Country = ifelse(Country %in% c('UK'), Country, 'Other')) %>%
    group_by(Country, Continent) %>%
    summarize(MyCount = sum(MyCount)) %>%
    select(Country, MyCount, Continent)

# A tibble: 2 x 3
# Groups:   Country [2]
   Country MyCount Continent
     <chr>   <dbl>    <fctr>
1   Other     425    Europe
2      UK     800    Europe

【讨论】:

    【解决方案3】:

    如果我正确地分析了您的样本,那么以下方法将是一种方法。您似乎想要来自欧洲的数据,然后将其汇总为 MyCount 中超过或等于 800 的国家和其他欧洲国家。如果是这样,您可以将 MyCount 中少于 800 个的欧洲国家的所有级别替换为“其他”并汇总数据。

    filter(myData, Continent == "Europe") %>%
    group_by(Country = fct_other(Country, keep = Country[MyCount >= 800])) %>%
    summarise(MyCount = sum(MyCount))
    
    #  Country MyCount
    #   <fctr>   <dbl>
    #1      UK     800
    #2   Other     425
    

    【讨论】:

      猜你喜欢
      • 2016-02-07
      • 2018-10-06
      • 2019-03-06
      • 2019-11-18
      • 2018-03-24
      • 1970-01-01
      • 2018-04-23
      • 2017-06-15
      • 2020-06-25
      相关资源
      最近更新 更多