如何进行逐行减法并将特定数字替换为零? [英] How to do row-wise subtraction and replace a specific number with zero?

查看:43
本文介绍了如何进行逐行减法并将特定数字替换为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

步骤1:我有一个简化的数据框,如下所示:

Step 1: I have a simplified dataframe like this:

df1 = data.frame (B=c(1,0,1), C=c(1,1,0)
  , D=c(1,0,1), E=c(1,1,0), F=c(0,0,1)
  , G=c(0,1,0), H=c(0,0,1), I=c(0,1,0))

  B C D E F G H I
1 1 1 1 1 0 0 0 0
2 0 1 0 1 0 1 0 1
3 1 0 1 0 1 0 1 0

步骤2:我想进行逐行减法,即(row1-row2),(row1-row3)和(row2-row3)

Step 2: I want to do row wise subtraction, i.e. (row1 - row2), (row1 - row3) and (row2 - row3)

row1-row2    1  0    1  0    0  -1   0  -1
row1-row3    0  1    0  1   -1   0  -1   0
row2-row3   -1  1   -1  1   -1   1  -1   1

步骤3 :将所有-1替换为0

step 3: replace all -1 to 0

row1-row2   1   0   1   0   0   0   0   0
row1-row3   0   1   0   1   0   0   0   0
row2-row3   0   1   0   1   0   1   0   1

您介意教我该怎么做吗?

Could you mind to teach me how to do so?

推荐答案

我喜欢使用 plyr 东西库像这样使用 combn 函数生成所有可能的行/列对。

I like using the plyr library for things like this using the combn function to generate all possible pairs of rows/columns.

require(plyr)
combos <- combn(nrow(df1), 2)

adply(combos, 2, function(x) {
  out <- data.frame(df1[x[1] , ] - df1[x[2] , ])
  out[out == -1] <- 0
  return(out)
  }
)

结果为:

  X1 B C D E F G H I
1  1 1 0 1 0 0 0 0 0
2  2 0 1 0 1 0 0 0 0
3  3 0 1 0 1 0 1 0 1

如有必要,可以删除第一列,plyr将其吐出自动为您服务。

If necessary, you can drop the first column, plyr spits that out automagically for you.

类似的问题:

  • Sum pairwise rows with R?
  • Chi Square Analysis using for loop in R
  • Compare one row to all other rows in a file using R

这篇关于如何进行逐行减法并将特定数字替换为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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