【问题标题】:Merging rows with the same name in R [duplicate]在R中合并具有相同名称的行[重复]
【发布时间】:2022-01-02 12:56:06
【问题描述】:

我必须用 R 为案例研究准备图表。我有一个包含数万行的数据集,其组织方式如下:

Platform | Profits

Desktop  |  608.50

Desktop  |  591.54

Desktop  |   83.21

Mobile   |   27.13

Mobile   |  133.81

Mobile   |  201.13

桌面版和移动版的行数及其利润比我发布的多出数万,但我想知道是否有办法将所有桌面版和移动版利润合并起来,以便生成的表格如下如下,以便我可以更轻松地绘制总数:

Platform | Profit

Desktop  |5839.01

Mobile   |4219.58

我尝试了子集、sumRows、sumCols,但似乎无法制作这种所需格式的表格。我可以 100% 同意将其分解为多个部分。

【问题讨论】:

    标签: r tidyr


    【解决方案1】:

    您可以使用以下代码

    library(tidyverse)
    
    df %>% 
      group_by(Platform) %>% 
      summarise(sum_profit = sum(Profits))
    

    输出

    # A tibble: 2 x 2
      Platform sum_profit
      <chr>         <dbl>
    1 Desktop       1283.
    2 Mobile         362.
    

    数据

    df = structure(list(Platform = c("Desktop", "Desktop", "Desktop", 
    "Mobile", "Mobile", "Mobile"), Profits = c(608.5, 591.54, 83.21, 
    27.13, 133.81, 201.13)), class = "data.frame", row.names = c(NA, 
    -6L))
    

    【讨论】:

    • 谢谢!我试过这个,但是控制台返回以下错误 > platformsValues %>% + group_by('Platform Type Name') %>% + summarise(sum = sum('Net Gross Booking Value USD')) 错误:@987654324 有问题@专栏sum。我sum = sum("Net Gross Booking Value USD")。 x 参数 i 的无效“类型”(字符)第 1 组发生错误:“平台类型名称”=“平台类型名称”。
    • 不要在变量名中保留空格,例如Platform Type NamePlatformTypeNamePlatform_Type_NameNet Gross Booking Value USDNetGrossBookingValueUSD 或者您可以使用问题中给出的较短的列名。
    • 我感觉间距是个问题,因为我必须把它放在引号中,但在 excel 表中就是这样,我应该只更改 excel 表吗?
    • 和like(platformsValues, 'Net Gross Booking Value USD') 一样?
    • 不使用反引号。
    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多