将不同数据框中的相同列名相乘

时间:2018-11-07 16:22:21

标签: r

我有两个数据框:一个包含原始值,另一个包含系数。我想创建一个执行以下计算的新数据框:standard_deviation *系数_of_variable * variable_value。然后,我想在这些新值的末尾附加字符串_decomp

df1

Standard_Deviation    Var1     Var2    Var3   Intercept
                10       4        5       9           1 
                10      12        7      11           1
                10      25        9       3           1
                10      12        8       1           1

df2

    names      coefficients
Intercept             -1.25
     Var1              0.08
     Var2              1.08
     Var3             -0.04

我希望我的最终输出看起来像这样:

       Var1_decomp     Var2_decomp    Var3_decomp   Intercept_decomp
       3.2                      54           -3.6              -12.5 
       9.6                    75.6           -4.4              -12.5
       20                     97.2           -1.2              -12.5
       9.6                    86.4           -0.4              -12.5

1 个答案:

答案 0 :(得分:2)

制作数据帧

df1 = read.table(text="Standard_Deviation    Var1     Var2    Var3   Intercept
                10       4        5       9           1 
                10      12        7      11           1
                10      25        9       3           1
                10      12        8       1           1", header = TRUE)

df2 = read.table(text="names      coefficients
Intercept             -1.25
     Var1              0.08
     Var2              1.08
     Var3             -0.04", header = TRUE)

您可以通过这种方式进行处理。

out = matrix(0, nrow = length(df1$Standard_Deviation), ncol = NCOL(df1) - 1)

for (i in 2:NCOL(df1)){
    j = which(df2$names == names(df1)[i])
    out[,i-1] = df1[,1] * df1[,i] * df2[j,2]
    }

colnames(out) = paste0(names(df1)[-1], "_decomp")