Laura Oh Chun Xing
Laura Oh Chun Xing

Reputation: 11

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. This is specified in the months column.

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.

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.

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

Upvotes: 1

Views: 49

Answers (3)

user14692575
user14692575

Reputation:

Slightly different base R approach with with():

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)

Upvotes: 0

Andrea M
Andrea M

Reputation: 2481

An alternative if for any reason you have to use base R is:

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)

Upvotes: 1

VvdL
VvdL

Reputation: 3230

Using dplyr:

library(dplyr)
df1 %>%
  mutate(cost = (12/months)*cost, 
         revenue = (12/months)*revenue)

Upvotes: 1

Related Questions