首页 文章

将特定列中每行的值转换为该特定列中特定行的值的百分比

提问于
浏览
3

我的数据框由财务报表中的数据组成(例如损益表,资产负债表,现金流量表),每行指的是财务报表条目(例如收入,利润),每列指的是特定年份 .

数据的一个例子如下:

variable <- c("Revenue", "Cost of Goods Sold", "Gross Profit", "SG&A", "Operating Income", "Interest Expense", 
          "Pretax Income", "Income Tax", "Net Income")
year_2014 <- c(6500, 3012, 3488, 1231, 2257, 231, 2026, 462, 1564)
year_2015 <- c(3250, 1323, 1927, 912, 1015, 109, 906, 209, 697)
year_2016 <- c(4965, 2723, 2242, 1159, 1083, 106, 977, 187, 790)
df <- data.frame(variable, year_2014, year_2015, year_2016)

我想对财务报表进行通用调整,我将每一行划分为收入 . 例如,在2014年,净收入为1564 /收入为6500 * 100.所得税为462 /收入为6500 * 100等 .

我正在寻找的最终结果看起来像这样:
Common Sized Income Statement

我已经尝试了多种方法来解决问题,但一切都行不通:

library(dplyr)

df <- df %>%
    mutate(percentage = year_2014/filter(select(year_2014), variable == "Revenue")

source表示我无法在mutate内过滤 .

我尝试使用子集符号来获取后续除法步骤的“收入”行,但它失败了:

df <- df %>%
    mutate(percentage = year_2014/variable["Revenue"])

我也搜索过Stackoverflow,但无法找到答案 . 我得到的"closest"答案是postpost . 然而,这些帖子是不同的,因为他们的数据集是长格式(与我的宽格式相反),他们的数据集由组(我没有"group_by")组成,我需要硬编码我参考的特定行 .

非常感激!谢谢!

1 回答

  • 4

    可以试试 dplyr::mutate_at . 此外,如果预计 Revenue 不是第1行,那么通用解决方案可以如下:

    library(dplyr)
    
    df %>% mutate_at(vars(starts_with("year")), 
                      funs(100*./.[which(variable == "Revenue")])) %>%
      as.data.frame()
    
    
    #             variable year_2014 year_2015 year_2016
    # 1            Revenue    100.00    100.00    100.00
    # 2 Cost of Goods Sold     46.34     40.71     54.84
    # 3       Gross Profit     53.66     59.29     45.16
    # 4               SG&A     18.94     28.06     23.34
    # 5   Operating Income     34.72     31.23     21.81
    # 6   Interest Expense      3.55      3.35      2.13
    # 7      Pretax Income     31.17     27.88     19.68
    # 8         Income Tax      7.11      6.43      3.77
    # 9         Net Income     24.06     21.45     15.91
    

相关问题