从列表列表中删除NA [英] Remove NA from list of lists

查看:74
本文介绍了从列表列表中删除NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵data.mat,它看起来像:

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

A B C D E  
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 within a bigger list. I do the following:

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

这会给我一个列表列表,其中包括NA,例如:

which gives me a list of lists, with NAs included, such as:

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

但是我想要的是:

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

在tapply调用过程中或之后,是否有删除NA的好方法?

Is there a good way to remove the NAs either during the tapply call or after the fact?

推荐答案

当然,您可以像这样使用lapply:

Sure, you can use lapply like this:

> 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

这篇关于从列表列表中删除NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆