如何对 data.table 的每一行进行点积
How to perform dot product on each row of a data.table
我有以下 data.table :
# id b c d
# 1: 1 -0.25174915 -0.2130797 -0.67909764
# 2: 2 -0.35569766 0.6014930 0.35201386
# 3: 3 -0.31600957 0.4398968 -1.15475814
# 4: 4 -0.54113762 -2.3497952 0.64503654
# 5: 5 0.11227873 0.0233775 -0.96891456
# 6: 6 1.24077566 -1.2843439 1.98883516
# 7: 7 -0.23819626 0.9950835 -0.17279980
# 8: 8 1.49353589 0.3067897 -0.02592004
# 9: 9 0.01033722 -0.5967766 -0.28536224
我想用从 PCA$rotation 矩阵获得的以下矩阵对每一行进行点积 == coefs
:
coefs
# PC1 PC2 PC3
#var1 x1 x2 x3
#var2 y1 y2 y3
#var3 z1 z2 z3
为了在我的 data.table 中获得一个新列,如下所示:
# id b c d results
# 1: 1 -0.25174915 -0.2130797 -0.67909764 x1*-0.25174915 + y1*-0.2130797 +z1*-0.67909764 + x2*-0.25174915 + y2*-0.2130797 + z2*-0.67909764 +x3*-0.25174915 + y3*-0.2130797 + z3*-0.67909764
# 2: 2 -0.35569766 0.6014930 0.35201386 x1*-0.35569766 + y1*0.6014930 +z1*0.35201386 + x2*-0.35569766 + y2*0.6014930 + z2*0.35201386 +x3*-0.35569766 + y3*0.6014930 + z3*0.35201386
# 3: 3 -0.31600957 0.4398968 -1.15475814
# 4: 4 -0.54113762 -2.3497952 0.64503654
# 5: 5 0.11227873 0.0233775 -0.96891456
# 6: 6 1.24077566 -1.2843439 1.98883516
# 7: 7 -0.23819626 0.9950835 -0.17279980
# 8: 8 1.49353589 0.3067897 -0.02592004
# 9: 9 0.01033722 -0.5967766 -0.28536224
你可以用apply
对每一行x
做x*coefs
,然后求和。向量 x
将按列与 coefs
相乘并被回收,这与您给出的公式相匹配。
df$results <- apply(df[-1], 1, function(x) sum(x*coefs))
我有以下 data.table :
# id b c d
# 1: 1 -0.25174915 -0.2130797 -0.67909764
# 2: 2 -0.35569766 0.6014930 0.35201386
# 3: 3 -0.31600957 0.4398968 -1.15475814
# 4: 4 -0.54113762 -2.3497952 0.64503654
# 5: 5 0.11227873 0.0233775 -0.96891456
# 6: 6 1.24077566 -1.2843439 1.98883516
# 7: 7 -0.23819626 0.9950835 -0.17279980
# 8: 8 1.49353589 0.3067897 -0.02592004
# 9: 9 0.01033722 -0.5967766 -0.28536224
我想用从 PCA$rotation 矩阵获得的以下矩阵对每一行进行点积 == coefs
:
coefs
# PC1 PC2 PC3
#var1 x1 x2 x3
#var2 y1 y2 y3
#var3 z1 z2 z3
为了在我的 data.table 中获得一个新列,如下所示:
# id b c d results
# 1: 1 -0.25174915 -0.2130797 -0.67909764 x1*-0.25174915 + y1*-0.2130797 +z1*-0.67909764 + x2*-0.25174915 + y2*-0.2130797 + z2*-0.67909764 +x3*-0.25174915 + y3*-0.2130797 + z3*-0.67909764
# 2: 2 -0.35569766 0.6014930 0.35201386 x1*-0.35569766 + y1*0.6014930 +z1*0.35201386 + x2*-0.35569766 + y2*0.6014930 + z2*0.35201386 +x3*-0.35569766 + y3*0.6014930 + z3*0.35201386
# 3: 3 -0.31600957 0.4398968 -1.15475814
# 4: 4 -0.54113762 -2.3497952 0.64503654
# 5: 5 0.11227873 0.0233775 -0.96891456
# 6: 6 1.24077566 -1.2843439 1.98883516
# 7: 7 -0.23819626 0.9950835 -0.17279980
# 8: 8 1.49353589 0.3067897 -0.02592004
# 9: 9 0.01033722 -0.5967766 -0.28536224
你可以用apply
对每一行x
做x*coefs
,然后求和。向量 x
将按列与 coefs
相乘并被回收,这与您给出的公式相匹配。
df$results <- apply(df[-1], 1, function(x) sum(x*coefs))