[英]Conditional calculations in dataframe based on values in other column R
I have a data.frame
where most, but not all, data are recorded over a 12-month period.我有一个
data.frame
,其中大部分(但不是全部)数据记录在 12 个月内。 This is specified in the months
column.这在
months
列中指定。
I need to transform the revenue
and cost
variables only (since they are flow data, compared to total_assets which is stock data) so I get the 12-month values.我只需要转换
revenue
和cost
变量(因为它们是流量数据,与作为库存数据的 total_assets 相比),所以我得到了 12 个月的值。
In this example, for Michael
and Ravi
I need to replace the values in revenue and cost by (12/months)*revenue
and (12/months)*cost
, respectively.在此示例中,对于
Michael
和Ravi
,我需要将收入和成本中的值分别替换为(12/months)*revenue
和(12/months)*cost
。
What would be a possible way to do this?有什么可能的方法来做到这一点?
df1 = data.frame(name = c('George','Andrea', 'Micheal','Maggie','Ravi'),
months=c(12,12,4,12,9),
revenue=c(45,78,13,89,48),
cost=c(56,52,15,88,24),
total_asset=c(100,121,145,103,119))
df1
name months revenue cost total_asset
1 George 12 45 56 100
2 Andrea 12 78 52 121
3 Micheal 4 13 15 145
4 Maggie 12 89 88 103
5 Ravi 9 48 24 119
Using dplyr:使用 dplyr:
library(dplyr)
df1 %>%
mutate(cost = (12/months)*cost,
revenue = (12/months)*revenue)
An alternative if for any reason you have to use base R is:如果出于任何原因您必须使用 base R,另一种选择是:
df1$revenue <- 12/df1$months * df1$revenue
df1$cost <- 12/df1$months * df1$cost
df1
#> name months revenue cost total_asset
#> 1 George 12 45 56 100
#> 2 Andrea 12 78 52 121
#> 3 Micheal 4 39 45 145
#> 4 Maggie 12 89 88 103
#> 5 Ravi 9 64 32 119
Created on 2022-06-01 by the reprex package (v2.0.1)由reprex 包于 2022-06-01 创建 (v2.0.1)
Slightly different base R approach with with()
:与
with()
略有不同的基本 R 方法:
df1 = data.frame(name = c('George','Andrea', 'Micheal','Maggie','Ravi'),
months=c(12,12,4,12,9),
revenue=c(45,78,13,89,48),
cost=c(56,52,15,88,24),
total_asset=c(100,121,145,103,119))
df1$revenue <- with(df1, 12/months * revenue)
df1$cost <- with(df1, 12/months * cost)
head(df1)
#> name months revenue cost total_asset
#> 1 George 12 45 56 100
#> 2 Andrea 12 78 52 121
#> 3 Micheal 4 39 45 145
#> 4 Maggie 12 89 88 103
#> 5 Ravi 9 64 32 119
Created on 2022-06-01 by the reprex package (v2.0.1)由reprex 包于 2022-06-01 创建 (v2.0.1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.