ROY ROY - 2 months ago 8
R Question

Create new columns based on mathematical calculation

I have a dataframe which looks like this:

df

X24_TT_1.1 X135_121.FTT_2.1 X1055_121.FTT_3.1
0.14 0.84 0.92
0.88 0.06 0.08
0.91 0.17 0.85
0.08 0.9 0.11
0.11 0.16 0.04
0.83 0.1 0.87


I want to create new columns which has same name with additional "_P" added at last and calculation formula is :

for column X24_TT_1.1 = 24 * (0.14/(1-0.14))

for column X135_121.FTT_2.1 = 135 * (0.84/(1-0.84))

for column X1055_121.FTT_3.1 = 1055 * (0.92/(1-0.92))

And finally it should look like this:

X24_TT_1.1 X135_121.FTT_2.1 X1055_121.FTT_3.1 X24_TT_1.2_P X135_121.FTT_2.2_P X1055_121.FTT_3.2_P
0.14 0.84 0.92 3.91 708.75 12132.50
0.88 0.06 0.08 176.00 8.62 91.74
0.91 0.17 0.85 242.67 27.65 5978.33
0.08 0.9 0.11 2.09 1215.00 130.39
0.11 0.16 0.04 2.97 25.71 43.96
0.83 0.1 0.87 117.18 15.00 7060.38


I want to do this dynamically as dataset has more than 100 columns

Answer

Try this:

x <- sapply(names(df), function(x) {
            s <- strsplit(x, "_")[[1]][1]
            s <- substring(s, 2, nchar(s))
            as.numeric(s)*(df[,x]/(1 - df[,x]))
     })


colnames(x) <- paste0(colnames(df), "_P")
cbind(df, round(x,2))

  X24_TT_1.1 X135_121.FTT_2.1 X1055_121.FTT_3.1 X24_TT_1.1_P X135_121.FTT_2.1_P X1055_121.FTT_3.1_P
1       0.14             0.84              0.92         3.91             708.75            12132.50
2       0.88             0.06              0.08       176.00               8.62               91.74
3       0.91             0.17              0.85       242.67              27.65             5978.33
4       0.08             0.90              0.11         2.09            1215.00              130.39
5       0.11             0.16              0.04         2.97              25.71               43.96
6       0.83             0.10              0.87       117.18              15.00             7060.38