sherek_66
sherek_66

Reputation: 531

how to multiply some elements of two columns?

Suppose there are 3 different columns:

PAYPR         UNIT                 ACTDUR
40       (4) Per month               60 
100      (5) Per hour                30 
50       (6) Per year                10
5        (1) Per day                 20

when UNIT column is '(5) Per hour' I want to do

 PAYPR<-PAYPR*ACTDUR/60 

So the output is

  PAYPR         UNIT                 ACTDUR
   40       (4) Per month               60 
100*30/60   (5) Per hour                30 
   50       (6) Per year                10
   5        (1) Per day                 20

Upvotes: 0

Views: 36

Answers (2)

Arturo Sbr
Arturo Sbr

Reputation: 6323

This can be done with other libraries, but I like to use data.table because the syntax is close to base data.frame, but simpler. Suppose your table is stored in ´dt´. Then:

library(data.table)
dt[UNIT == "(5) Per hour", PAYPR := PAYPR * ACTDUR / 60]

This is called a slice. It can be done with base R too, but I think the syntax is sloppy:

dt[dt$UNIT == "(5)", "PAYPR"] <- dt[dt$UNIT == "(5)", "PAYPR"] * dt[dt$UNIT == "(5)", "ACTDUR"] / 30

I think this last line could be synthesized a bit, but you get the gist of it.

Upvotes: 1

akrun
akrun

Reputation: 886948

Create a logical index and modify the values of 'PAYPR' based on that in base R

i1 <- df1$UNIT == "(5) Per hour"
df1$PAYPR[i1] <- df1$PAYPR[i1]* df1$ACTDUR[i1]/60
df1
#  PAYPR          UNIT ACTDUR
#1    40 (4) Per month     60
#2    50  (5) Per hour     30
#3    50  (6) Per year     10
#4     5   (1) Per day     20

data

df1 <- structure(list(PAYPR = c(40L, 100L, 50L, 5L), UNIT = c("(4) Per month", 
"(5) Per hour", "(6) Per year", "(1) Per day"), ACTDUR = c(60L, 
30L, 10L, 20L)), class = "data.frame", row.names = c(NA, -4L))

Upvotes: 1

Related Questions