Home > OS >  Conditional calculations in dataframe based on values in other column R
Conditional calculations in dataframe based on values in other column R

Time:06-02

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

CodePudding user response:

Using dplyr:

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

CodePudding user response:

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)

CodePudding user response:

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)

  •  Tags:  
  • r
  • Related