使用数据框 df
如下所示
text <- "
Parameter,Dec-17,Sep-17,Jun-17,Mar-17,Dec-16
Income,12112,13323.2,14655.52,16121.072,17733.1792
Cost,10900.8,11990.88,13189.968,14508.9648,15959.86128
"
df <- read.table(textConnection(text), sep=",", header = T, stringsAsFactors = F)
df
Parameter Dec.17 Sep.17 Jun.17 Mar.17 Dec.16
1 Income 12112.0 13323.20 14655.52 16121.07 17733.18
2 Cost 10900.8 11990.88 13189.97 14508.96 15959.86
我想再添加两行,1- Profit
(Income - Cost
) 和 2 - Tax
( 0.2*每个季度的利润
)- 12 月 17 日、9 月 17 日、6 月 17 日、3 月 17 日、12 月 16 日
我怎么知道这个 - dplyr
是首选。 Base R 解决方案也会有所帮助。
预期输出
Parameter Dec.17 Sep.17 Jun.17 Mar.17 Dec.16
1 Income 12112.00 13323.200 14655.5200 16121.0720 17733.1792
2 Cost 10900.80 11990.880 13189.9680 14508.9648 15959.8613
3 Profit 1211.20 1332.320 1465.5520 1612.1072 1773.3179
4 Tax 242.24 266.464 293.1104 322.4214 354.6636
最佳答案
也许不是最优雅的,但这是一个 dplyr 解决方案。最后的select
是获取与原表相同的列序。
df %>%
gather(key = month, value = amount, -Parameter) %>%
spread(Parameter, amount) %>%
mutate(Profit = Income - Cost) %>%
mutate(Tax = 0.2 * Profit) %>%
gather(key = Parameter, value = amount, -month) %>%
spread(month, value = amount) %>%
select(names(df))
Parameter Dec.17 Sep.17 Jun.17 Mar.17 Dec.16
1 Cost 10900.80 11990.880 13189.9680 14508.9648 15959.8613
2 Income 12112.00 13323.200 14655.5200 16121.0720 17733.1792
3 Profit 1211.20 1332.320 1465.5520 1612.1072 1773.3179
4 Tax 242.24 266.464 293.1104 322.4214 354.6636
关于r - 使用从现有行计算的值向数据框添加新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48608217/