在一个数据帧中将行(带有行名称)乘以其他列中的匹配列名称

编程入门 行业动态 更新时间:2024-10-26 07:30:06
本文介绍了在一个数据帧中将行(带有行名称)乘以其他列中的匹配列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个数据框:

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)

更多推荐

在一个数据帧中将行(带有行名称)乘以其他列中的匹配列名称

本文发布于:2023-10-30 18:56:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1543710.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   在一   中将   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!