Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将数据帧乘以另一个df中的x向量,返回x个新数据帧_R - Fatal编程技术网

R 将数据帧乘以另一个df中的x向量,返回x个新数据帧

R 将数据帧乘以另一个df中的x向量,返回x个新数据帧,r,R,我有两个数据帧: df1 = data.frame("a" = c(.2, 0, .3), "b" = c(.3, .1, .4), "c" = c(.5,.9, .3)) df2 = data.frame("X"= c(41, 40, 100), "Y" = c(19, 20, 15), "Z" = c(8, 6, 10)) 很容易将df1的每一行乘以df2第一列的对应行: 然后对各列求和: dfX = colSums(dfX) 返回 a b c 38.2 56.3 86

我有两个数据帧:

df1 = data.frame("a" = c(.2, 0, .3), "b" = c(.3, .1, .4), "c" = c(.5,.9, .3))
df2 = data.frame("X"= c(41, 40, 100), "Y" = c(19, 20, 15), "Z" = c(8, 6, 10))
很容易将df1的每一行乘以df2第一列的对应行:

然后对各列求和:

dfX = colSums(dfX)
返回

  a    b    c 
38.2 56.3 86.5 
如何对df2中的每一列执行此操作,生成数据帧dfX、dfY、dfZ等。?然后,我想对这些新数据帧进行行绑定,然后进行转置,生成:

    X    Y    Z
a 38.2  8.3  4.6
b 56.3 13.7  7.0
c 86.5 32.0 12.4
我们可以使用sapply将df2的每一列与df1相乘,然后对它们进行colSums运算

sapply(df2, function(x) colSums(df1 * x))

#    X    Y    Z
#a 38.2  8.3  4.6
#b 56.3 13.7  7.0
#c 86.5 32.0 12.4
我们可以使用sapply将df2的每一列与df1相乘,然后对它们进行colSums运算

sapply(df2, function(x) colSums(df1 * x))

#    X    Y    Z
#a 38.2  8.3  4.6
#b 56.3 13.7  7.0
#c 86.5 32.0 12.4

我们可以用crossproduct来实现这一点

t(df1) %*% as.matrix(df2)
#     X    Y    Z
#a 38.2  8.3  4.6
#b 56.3 13.7  7.0
#c 86.5 32.0 12.4

我们可以用crossproduct来实现这一点

t(df1) %*% as.matrix(df2)
#     X    Y    Z
#a 38.2  8.3  4.6
#b 56.3 13.7  7.0
#c 86.5 32.0 12.4

太好了,谢谢!data.framelapplydf2,函数x trbindcolSumsdf1*x似乎负责rest@hoho我刚刚添加了一个更简化的版本。太好了,谢谢!data.framelapplydf2,函数x trbindcolSumsdf1*x似乎负责rest@hoho我只是添加了一个更简化的版本。