Home > Mobile >  Conditional multiplication of column
Conditional multiplication of column

Time:06-04

I have two columns. One is sales (sales_usd) and the other (sales_unit) indicates whether or not the sales amount is in millions (M) or billions (B): the data

I'm just trying to get everything in billions so if there is an "M" in the units column I want to divide the respective cells in the sales_usd column by 1000.

So far I have

data$sales_usd <- if(data$sales_unit="M")
{
  data$sales_usd / 1000
  }

but the data remains the same.

CodePudding user response:

In base R:

 df$sales_usd <- ifelse(df$sales_unit == "M", # condition
                        df$sales_usd/1000,    # what if condition is TRUE
                        df$sales_usd          # what if condition is FALSE
                        )

CodePudding user response:

This should work

library(dplyr)

data |> 
  mutate(sales=ifelse(sales_unit=="M",sales_usd/1000,sales_usd))
  • Related