Davide Bottoli
Davide Bottoli

Reputation: 91

Operation on a column with filtering in R

I've a simple question: suppose that I would like to make an operation on one column (in this case multiplying by 1000 column Measure) according to the value of another column (in this case when Unit is equal to L).

Is there any efficient way to do?

I'll report a simple example but you don't have to focus on changing the name of the value of the second column.

Input:

a <- data.frame(Measure = c(10, 2000, 10000, 15, 40), 
                Unit = c("L","mL","mL","L","L"), 
                Price = c(100, 200, 500, 700, 900 ))

Expected Output:

b <- data.frame(Measure = c(10000, 2000, 10000, 15000, 40000), 
                Unit = c("mL","mL","mL","mL","mL"), 
                Price = c(100, 200, 500, 700, 900 ))

Upvotes: 1

Views: 416

Answers (3)

Frank
Frank

Reputation: 66819

library(data.table)
DT = data.table(a)

DT[Unit == "L", `:=`(Measure = Measure * 1000, Unit = "mL")]

   Measure Unit Price
1:   10000   mL   100
2:    2000   mL   200
3:   10000   mL   500
4:   15000   mL   700
5:   40000   mL   900

The syntax is DT[i, j]:

  1. Filter to rows using i
  2. Do j

The := function is used to edit columns.

Upvotes: 2

mysteRious
mysteRious

Reputation: 4314

Same as above, only the tidyverse/dplyr way:

> library(dplyr)
> a %>% mutate(Measure=ifelse(Unit=="mL",Measure,(Measure*1000)))
  Measure Unit Price
1   10000    L   100
2    2000   mL   200
3   10000   mL   500
4   15000    L   700
5   40000    L   900

Upvotes: 1

Lennyy
Lennyy

Reputation: 6132

With below code you only multiply Measure by 1000 when Unit is "L"; in all other cases just the Measure value is returned without a multiplication

a <- data.frame(Measure = c(10, 2000, 10000, 15, 40), 
            Unit = c("L","mL","mL","L","L"), 
            Price = c(100, 200, 500, 700, 900 ))



 a$Measure <- ifelse(a$Unit == "L", a$Measure * 1000, a$Measure)
 a
   Measure Unit Price
 1   10000    L   100
 2    2000   mL   200
 3   10000   mL   500
 4   15000    L   700
 5   40000    L   900

Upvotes: 1

Related Questions