dimanche 14 avril 2019

Conditionally assign values to two columns at once R

Problem:

Is there a way to write a single command to assign different values to two columns of a row that meets one condition?

Context:

I have to conditionally assign a value to two columns: Quantity and Price. I want to do this using the data.table library in R.

My dataset looks like this:

> example
tariff  expenditure  
     1           50
     2           70
     3           50

Each tariff has different prices. Thus, a single expenditure can result in different consumption quantities.

Suppose the prices of tariffs 1, 2 and 3 are 10, 20 and 30 respectively. I want to do the following in a single expression:

  1. If tariff is 1, then Consumption is expenditure/10 and Price is 10.
  2. If tariff is 2, then Consumption is expenditure/20 and price is 20.
  3. If tariff is 3, then Consumption is expenditure/30 and Price is 30.

In data.table, this can be done by slicing example as follows:

example[tariff == 1, c("Consumption", "Price") := list(expenditure / 10, 10)]

In the real dataset, Consumption and Price depend on the value of many other columns besides tariff. If I proceed as shown above, I will end up with about 100 different boolean slices. I'd much rather do this using ifelse.

The following code failed:

example[, c("Consumption", "Price") := ifelse(tariff == 1, list(expenditure/10, 10),
                                              ifelse(tariff == 2, list(expenditure/20, 20),
                                                     list(expenditure/30, 30)))]

Is there a way to do this?

Aucun commentaire:

Enregistrer un commentaire