如何进行逐行减法并将特定数字替换为零?
步骤1:我有一个像这样的简化数据框:
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)
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
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
可以你介意教我怎么做吗?
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
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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我喜欢使用
plyr
库来完成类似的事情,使用combn
函数生成所有可能的行/列对。结果:
如有必要,您可以删除第一列,plyr 会自动为您吐出该列。
类似问题:
I like using the
plyr
library for things like this using thecombn
function to generate all possible pairs of rows/columns.Results in:
If necessary, you can drop the first column, plyr spits that out automagically for you.
Similar questions:
作为记录,我会这样做:
这会产生(上面的最后一行是一些糖,可能不需要):
这是完全矢量化的,并利用索引来扩展/提取 df1 的元素> 逐行操作所需。
For the record, I would do this:
This yields (the last line above is a bit of sugar, and may not be needed):
Which is fully vectorised and exploits indices to extend/extract the elements of
df1
required for the row-by-row operation.如果您想将行的名称更改为示例中的行名称:
最后,如果提前不知道行数,则可以执行以下操作:
If you'd like to change the name of the rows to those in your example:
Finally, if the number of rows is not known ahead of time, the following should do the trick: