[英]Remove NA from list of lists
I have a matrix, data.mat, that looks like: 我有一个矩阵data.mat,看起来像:
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)
which gives me a list of lists, with NAs included, such as: 这给了我一个包含NA的列表列表,例如:
$`1`
[1] 45 43 45 65 23
$`2`
[1] 12 45 56 NA NA
$`3`
[1] 13 4 34 12 NA
But what I want is: 但我想要的是:
$`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 the NAs either during the tapply call or after the fact? 是否有一种很好的方法可以在tapply呼叫期间或之后删除NA?
Sure, you can use lapply
like this: 当然,你可以像这样使用lapply
:
> 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
Your sample data: 您的样本数据:
data.mat <- data.matrix(read.table(text = "A B C D E
45 43 45 65 23
12 45 56 NA NA
13 4 34 12 NA ", header = TRUE))
To split by row: 按行拆分:
row.list <- split(data.mat, row(data.mat))
To remove NAs: 删除NA:
Map(Filter, list(Negate(is.na)), row.list)
or 要么
lapply(row.list, Filter, f = Negate(is.na))
Everything in one shot: 一拍一切:
Map(Filter, list(Negate(is.na)), split(data.mat, row(data.mat)))
You could do this: 你可以这样做:
apply(data.mat, 1, function(x) x[!is.na(x)])
Output: 输出:
[[1]]
A B C D E
45 43 45 65 23
[[2]]
A B C
12 45 56
[[3]]
A B C D
13 4 34 12
If you don't want names: 如果你不想要名字:
apply(data.mat, 1, function(x) unname(x[!is.na(x)]))
If there is the possibility that every row has the same number of NAs, it will be safer to use: 如果每行都有相同数量的NA,则使用起来会更安全:
split(apply(data.mat, 1, function(x) unname(x[!is.na(x)])), 1:nrow(data.mat))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.