R中数据帧的条件总和 [英] Conditional sum of data frames in R

查看:35
本文介绍了R中数据帧的条件总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想合并数据帧并根据其中一个数据帧的值有条件地计算它们的总和。

I want to combine data frames and calculate their sum conditionally depending on the value of one of the data frames.

对于以下示例,如果 df4 不为0且不为NA,总和应为 df3 + df4 否则应为 df1 + df2 + df3

For the example below, if a cell in df4 is not 0 and not NA, the sum should be df3 + df4 else the sum should be df1 + df2 + df3.

> df1
  1 2 3
A 0 3 2
B 1 1 0
C 5 0 2

> df2
  1 2 3
A 3 2 2
B 4 3 4
C 1 0 3

> df3
  1 2 3
A 1 3 4
B 3 4 3
C 1 2 3

条件取决于此框架:

> df4
   1  2  3
A  6  0  0
B  0  0 NA 
C NA  4  0

在上面的示例中,这是预期的结果。

With the above examples, this is the expected result:

> dfsum
  1 2 3
A 7 8 8
B 8 8 7
C 7 6 8

如何在R中执行此操作?

How do I do this in R?

推荐答案

m1 <- matrix(c(0,1,5,3,1,0,2,0,2),3)
m2 <- matrix(c(3,4,1,2,3,0,2,4,3),3)
m3 <- matrix(c(1,3,1,3,4,2,4,3,3),3)
m4 <- matrix(c(6,0,NA,0,0,4,0,NA,0),3)

msum <- m3 + m4
temp <- m1 + m2 + m3
cond <- is.na(m4) | m4==0

msum[cond] <- temp[cond]

#     [,1] [,2] [,3]
#[1,]    7    8    8
#[2,]    8    8    7
#[3,]    7    6    8

这篇关于R中数据帧的条件总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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