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

标签 r dplyr

我有一个数据框,其中包含来自财务报表(例如损益表、 Assets 负债表、现金流量表)的数据,每一行都引用一个财务报表条目(例如收入、利润),每一列都引用一个特定的年。

数据示例如下:

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,但找不到答案。我得到的“最接近”答案是这个 post还有这个post .然而,这些帖子是不同的,因为它们的数据集是长格式的(与我的宽格式相反),它们的数据集由组组成(我没有什么可以“group_by”),我需要对我正在制作的特定行进行硬编码引用。

非常感谢!谢谢!

最佳答案

可以试试 dplyr::mutate_at。此外,如果 Revenue 预计不会出现在第一行,那么通用解决方案可以是:

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

关于r - 将特定列中每一行的值转换为该特定列中特定行的值的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50541550/

相关文章:

从R sf中的多边形中移除孔

在 R 中随机化裂区(和其他经典设计)

R:将曲线拟合到点:使用什么线性/非线性模型?

r - 使用 roxygen2 记录新的 "+"S3 方法时出现问题

r - ggplot : Save multiple plots in one pdf with the same plot proportions

r - 从数据框中提取最高的正值和负值,并使用 R 将它们填充到格式化文本中

R dplyr 的 group_by 也考虑空组

按两列排名并保持联系

r - 如何将 fct_relevel 与 mutate_at 语法结合使用

r - 同时为两列申请 `mutate_at`?