【问题标题】:How to merge two rows in R?如何合并R中的两行?
【发布时间】:2022-01-15 16:53:03
【问题描述】:

我想知道 R 中是否有一个函数可以帮助我合并两行。现在我的数据是以下形状

Car_Type Prod Sale Month
Civic 120 67 June
City 192 112 June

如果可能,我希望数据采用这种形状:

Car_Type Prod Sale Month
Civic + City 312 179 June

我已经尝试过聚合函数,它可以工作,但它不会操纵整个数据框。

任何线索将不胜感激。谢谢!

【问题讨论】:

  • df %>% group_by(Month) %>% summarise(Prod = sum(Prod), Sale = sum(Sale), Car_Type = paste0(Car_Type, collapse=" + "))

标签: r dataframe dplyr tidyverse


【解决方案1】:

这是一个dplyr 解决方案。它使用辅助函数f 来区分数字和字符向量的情况,并应用必要的转换。

library(dplyr)

f <- function(x){
  if(is.numeric(x))
    sum(x)
  else if(any(x[-1] != x[1]))
    paste(x, collapse = "+")
  else x[1]
}

df1 %>%
  group_by(Month) %>%
  summarise(across(everything(), f)) %>%
  relocate(Month, .after = last_col())
## A tibble: 1 x 4
#  Car_Type    Prod  Sale Month
#  <chr>      <int> <int> <chr>
#1 Civic+City   312   179 June 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 2021-11-27
    • 2021-11-23
    • 2021-11-27
    相关资源
    最近更新 更多