dataframecalculated-columns

Add a column and fill with the value calculated using values from other columns


I am a newer in R. I want to add a column 'GFR' to the dataframe, and fill the column with the values calculated using GFR = 175 ✖️ (SCR^-1.154) ✖️ (age^-0.203) ✖️ 1.212[if Race = 3] ✖️ 0.742[if Gender = 1].

Here is my dataframe: ID Gender Age Race SCR 1 93735 1 52 2 11.46 2 93830 1 67 0 6.34 3 93834 2 48 3 0.64 4 93851 2 74 3 1.07 5 93893 1 55 0 2.40 6 94017 1 54 3 3.01 7 94050 2 55 3 0.93 8 94073 1 69 0 1.46 9 94095 2 78 0 NA 10 94179 1 72 3 1.90 11 94348 1 80 3 1.62 12 94500 2 60 0 1.25 13 94634 2 80 3 1.19 14 94670 1 60 0 1.62 15 94677 2 25 3 0.77 16 94711 2 64 1 0.90 17 94724 2 80 3 1.22 18 94725 1 56 3 NA 19 94729 1 37 0 1.87 20 94750 1 80 3 1.34 21 94753 2 74 0 0.86 22 94792 1 66 0 7.43 23 94813 2 62 0 0.62 24 94847 2 80 0 2.16 25 94894 1 50 3 0.98 picture of the datafram

I can add a column by using: dataframe$GFR <- rep(NA, nrow(dataframe))

and I can just write out 'dataframe1['GFR'] = 175 * dataframe1['SCR'] * dataframe1['Age']'

But I don't how to deal with: GFR = 175 ✖️ (SCR^-1.154) ✖️ (age^-0.203) ✖️ 1.212[if Race = 3] ✖️ 0.742[if Gender = 1].


Solution

  • But I don't how to deal with: GFR = 175 ✖️ (SCR^-1.154) ✖️ (age^-0.203) ✖️ 1.212[if Race = 3] ✖️ 0.742[if Gender = 1].

    You can use logical indexing:

    df$GFR = 175 * df$SCR^-1.154 * df$Age^-0.203
    df[df$Race==3,]$GFR = df[df$Race==3,]$GFR * 1.212
    df[df$Gender==1,]$GFR = df[df$Gender==1,]$GFR * 0.742