Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

r - Remove NA/NaN/Inf in a matrix

I want to try two things :

  1. How do I remove rows that contain NA/NaN/Inf
  2. How do I set value of data point from NA/NaN/Inf to 0.

So far, I have tried using the following for NA values, but been getting warnings.

> eg <- data[rowSums(is.na(data)) == 0,]
 Error in rowSums(is.na(data)) : 
       'x' must be an array of at least two dimensions
     In addition: Warning message:
     In is.na(data) : is.na() applied to non-(list or vector) of type 'closure'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I guess I'll throw my hat into the ring with my preferred methods:

# sample data
m <- matrix(c(1,2,NA,NaN,1,Inf,-1,1,9,3),5)
# remove all rows with non-finite values
m[!rowSums(!is.finite(m)),]
# replace all non-finite values with 0
m[!is.finite(m)] <- 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...