Remove NA from the list of lists

I have a data.mat matrix that looks like this:

ABCDE 45 43 45 65 23 12 45 56 NA NA 13 4 34 12 NA 

I am trying to turn this into a list of lists, where each row is one list in a larger list. I do the following:

 list <- tapply(data.mat,rep(1:nrow(data.mat),ncol(data.mat)),function(i)i) 

which gives me a list of lists with NA enabled, for example:

 $`1` [1] 45 43 45 65 23 $`2` [1] 12 45 56 NA NA $`3` [1] 13 4 34 12 NA 

But I want:

 $`1` [1] 45 43 45 65 23 $`2` [1] 12 45 56 $`3` [1] 13 4 34 12 

Is there a good way to remove NS during a call or after a fact?

+5
source share
3 answers

Of course you can use lapply as follows:

 > lapply(list, function(x) x[!is.na(x)]) $`1` [1] 45 43 45 65 23 $`2` [1] 12 45 56 $`3` [1] 13 4 34 12 
+11
source

Your data:

 data.mat <- data.matrix(read.table(text = "ABCDE 45 43 45 65 23 12 45 56 NA NA 13 4 34 12 NA ", header = TRUE)) 

Divide by line:

 row.list <- split(data.mat, row(data.mat)) 

To remove NA:

 Map(Filter, list(Negate(is.na)), row.list) 

or

 lapply(row.list, Filter, f = Negate(is.na)) 

All in one frame:

 Map(Filter, list(Negate(is.na)), split(data.mat, row(data.mat))) 
+4
source

You can do it:

 apply(data.mat, 1, function(x) x[!is.na(x)]) 

Exit:

 [[1]] ABCDE 45 43 45 65 23 [[2]] ABC 12 45 56 [[3]] ABCD 13 4 34 12 

If you do not need names:

 apply(data.mat, 1, function(x) unname(x[!is.na(x)])) 

If it is likely that each row has the same number of NS, it will be safer to use:

 split(apply(data.mat, 1, function(x) unname(x[!is.na(x)])), 1:nrow(data.mat)) 
+2
source

Source: https://habr.com/ru/post/1202288/


All Articles