bvowe
bvowe

Reputation: 3394

Multiply columns

Sample data

data=data.frame("a1" = c(11:14,NA),
                "a2"=c(23:27),
                "b1"=c(0,0,1,1,1),
                "b2"=c(1,1,0,0,1),
                "WANT1" = c(0,0,13,14,NA),
                "WANT2" = c(23,24,0,0,27))

The data has a1 a2 b1 b2. I want to create WANT1 and WANT2. WANT1=a1 times b1. WANT2 equals to a2 times b2. Is there a way to calculate this all at once?

I did

WANT1 = a1*b1

and this seems to work but I have this for many many rows so is there a more effective way?

Upvotes: 0

Views: 55

Answers (1)

Rushabh Patel
Rushabh Patel

Reputation: 2764

You could simply do-

data=data.frame("a1" = c(11:14,NA),
                "a2"=c(23:27),
                "b1"=c(0,0,1,1,1),
                "b2"=c(1,1,0,0,1))


> data.table::setDT(data)[,c("want1","want2"):= list(a1*b1,a2 *b2)]
> data
   a1 a2 b1 b2 want1 want2
1: 11 23  0  1     0    23
2: 12 24  0  1     0    24
3: 13 25  1  0    13     0
4: 14 26  1  0    14     0
5: NA 27  1  1    NA    27

Upvotes: 1

Related Questions