如何使用2个矩阵值中的1个替换NaN和Inf?

时间:2015-09-05 04:33:19

标签: r matrix replace nan

我有2个大型矩阵,包含100列和10,000行。我试图将a除以b并计算log2,然后计算abs()。

a<-c(2,0,2,3,0,6)
b<-c(0,1,4,6,0,6)
a/b
Inf 0.0 0.5 0.5 NaN 1.0

我想使用“2”代替“Inf”并使用“0”代替NaN。

2 个答案:

答案 0 :(得分:2)

你可以这样做:

res <- a/b;
res[is.infinite(res)] <- a[is.infinite(res)];
res[is.nan(res)] <- 0;

虽然,请注意,is.nan的文档说:

Computations involving ‘NaN’ will return ‘NaN’ or perhaps ‘NA’:
which of those two is not guaranteed and may depend on the R
platform (since compilers may re-order computations).

我虽然得到NaN

答案 1 :(得分:2)

在我看来,你只是不想除以0而b==0只返回相应的a值。如果是这种情况,则无需在InfNaN上工作:只需将b中的0替换为1。

b[b==0]<-1
a/b
#[1] 2.0 0.0 0.5 0.5 0.0 1.0