Veraaa Veraaa - 1 year ago 183
R Question

Compare two columns and replace value in R

I want to compare the values of two columns in R. If the damage free days (dfd) are bigger or the same as the total days column (TotalDays) then I want to replace the dfy value to Age (this is in days) - TotalDays.

I've seen different questions about this but nothing has seemed to work so far. I'd be really grateful if anyone could help!

Example columns:

dfy TotalDays age
7305.00 2872.21 10261
2556.75 3001.43 10210
3215.31 2941.87 12931

Example of what I want to achieve:
(dfy is replaced with age - TotalDays)

dfy TotalDays age
7433.79 2872.21 10261
2556.75 3001.43 10210
9988.13 2941.87 12931

Reproducible code:

df <- data.frame(dfy=c(7305.00,2556.75,3215.31),
TotalDays = c(2872.21, 3001.43, 2941.87), age = c(10261, 10210, 12931))

Answer Source

We can create a logical vector and replace only those elements in 'dfy' that are TRUE for that vector.

i1 <- with(df, TotalDays < dfy)
df$dfy[i1] <- with(df, age[i1] - TotalDays[i1])

A faster option would be using data.table by assigning (:=) in place

setDT(df)[TotalDays < dfy, dfy := age - TotalDays]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download