Carlo
Carlo

Reputation: 597

How to remove NA from each row

I have the following data:

data = structure(c(NA, NA, 42.5118650772641, 14.5479065259077, -1.8082256603085, 
23.5107343175811, 53.5663302164282, 29.9776538834842, -3.86496086519614, 
29.0845645318778, 97.3528292018692, 23.3881957633757, 54.8844183666383, 
28.4301700493692, 3.53001924175695, 15.8256931567166, 23.6987392522877, 
12.1185979190016, 2.48432380993373, 23.1776787033568, 30.0735375165638, 
10.6297705564003), .Dim = c(2L, 11L))

And I need to eliminate each NA element in the rows. If I try to do

rem_NA =  data[!is.na(data)]

It will delete the NAs, but i will obtain a vector, but I don't want to lose the matrix form.

the output i would like to have is equal to:

data1 = data[,-1]

Upvotes: 3

Views: 325

Answers (3)

akrun
akrun

Reputation: 887028

An option with Filter after converting to data.frame

Filter(function(x) any(!is.na(x)), as.data.frame(data))

Upvotes: 1

Uwe
Uwe

Reputation: 42544

If I understand correctly from OP's comment, the positions of the NA values can be arbitrarily scattered but each row has the same number of NA values.

Here is an example for such a matrix:

m <- matrix(c(NA, 2, 3, 4, 5, NA), nrow = 2L, byrow = TRUE)
m
     [,1] [,2] [,3]
[1,]   NA    2    3
[2,]    4    5   NA

The NA values can be eliminated row-wise by

t(apply(m, 1L, na.omit))
     [,1] [,2]
[1,]    2    3
[2,]    4    5

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

The following option seems to work:

data[, colSums(is.na(data)) < nrow(data)]

The logic here is to retain any column for which the number of NA values is strictly less than the number of rows. The first column in your sample data fails this condition, because there are two rows and also two NA values.

Upvotes: 4

Related Questions