在一个数据帧中将行(带有行名称)乘以其他列中的匹配列名称 [英] Multiply rows (with row names) in one data frame with matching column names in another

查看:160
本文介绍了在一个数据帧中将行(带有行名称)乘以其他列中的匹配列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据框:

df1 <- data.frame(Values=c(0.01,0.05), row.names=c("X", "Y"))
df1
  Values
X   0.01
Y   0.05

df2 <-data.frame(c(0,1,1), c(1,0,0), c(1,1,1))
colnames(df2) <- c("X","Y","Z")

df2
  X Y Z
1 0 1 1
2 1 0 1
3 1 0 1

我希望在df2上执行横向操作,在每个列乘以在df2中,其df1中的对应行,然后执行求和

I wish to perform a rowwise operation on df2, where I multiply every column in df2 with its corresponding row in df1 and then perform a summation.

例如,对于df2的第1行,我想计算:

For example, for row 1 of df2, I wish to calculate:

df2 %>% rowwise %>% mutate(newVAL=(df1["X",]*df2[1,"X"])+(df1["Y",]*df2[1,"Y"]))

,同时排除不匹配的列(df1中的行)或具有NAs 。

while excluding columns that don't match (rows in df1) or have NAs.

df1中有几千行,df2中有数千行。

I have several thousands of rows in df1 and several thousands of rows and columns in df2.

任何帮助非常感谢!

PS。我已经在Perl中使用哈希实现了这一点,并且正在使用system()调用来在Rmarkdown文档中执行这些计算。为了保持完全可重现性,我正在尝试在R中重做。如果需要,快乐分享Perl代码。

PS. I have implemented this in Perl using hashes and was using the system() call to perform these calculations within an Rmarkdown document. In order to keep it completely reproducible, I am trying to redo it in R. Happy to share the Perl code if necessary.

谢谢。

推荐答案

如果我理解正确,看起来您需要 sweep

If I understand correctly, it looks like you need sweep.

df3 <- sweep(df2[, rownames(df1)], 2, t(df1), '*')
df3$total <- rowSums(df3)

这篇关于在一个数据帧中将行(带有行名称)乘以其他列中的匹配列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆