将 NA 移动到矩阵中每一列的开头 [英] Move NA to the start of each column in a matrix

查看:73
本文介绍了将 NA 移动到矩阵中每一列的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含如下数据的矩阵:

I have a matrix with data such as below:

col1 col2 col3 col4 col5
2    3    2    8    3
7    1    0    4    NA
5    8    1    NA   NA
9    6    NA   NA   NA
4    NA   NA   NA   NA

我想将数据重新排列为以下结果,基本上将 NA 移动到每列的顶部:

I want to rearrange the data to the following outcome, basically moving the NA to the top of each column:

col1 col2 col3 col4 col5
2    NA   NA   NA   NA
7    3    NA   NA   NA
5    1    2    NA   NA
9    8    0    8    NA
4    6    1    4    3

如您所见,新数据的排序向量基于此排序矩阵:

As you can see, the ordering vectors for the new data is based on this ordering matrix:

col1 col2 col3 col4 col5
1    5    4    3    2
2    1    5    4    3
3    2    1    5    4 
4    3    2    1    5 
5    4    3    2    1

我认为最好的方法是将排序矩阵应用于原始矩阵,因此col1排序向量排序col1,col2排序向量排序col2,依此类推.

I think the best way is to apply the ordering matrix to the original matrix, so col1 ordering vector orders col1, and col2 ordering vector orders col2, and so on.

推荐答案

使用此数据

your_matrix = structure(c(2L, 7L, 5L, 9L, 4L, 3L, 1L, 8L, 6L, NA, 2L, 0L, 1L, 
NA, NA, 8L, 4L, NA, NA, NA, 3L, NA, NA, NA, NA), .Dim = c(5L, 
5L), .Dimnames = list(NULL, c("col1", "col2", "col3", "col4", 
"col5")))

your_matrix
#      col1 col2 col3 col4 col5
# [1,]    2    3    2    8    3
# [2,]    7    1    0    4   NA
# [3,]    5    8    1   NA   NA
# [4,]    9    6   NA   NA   NA
# [5,]    4   NA   NA   NA   NA

我们可以应用一个将 NA 移到末尾的排序函数:

We can apply an ordering function that moves NAs to the end:

apply(your_matrix, MARGIN = 2, FUN = function(x) x[order(!is.na(x))])
#      col1 col2 col3 col4 col5
# [1,]    2   NA   NA   NA   NA
# [2,]    7    3   NA   NA   NA
# [3,]    5    1    2   NA   NA
# [4,]    9    8    0    8   NA
# [5,]    4    6    1    4    3

这篇关于将 NA 移动到矩阵中每一列的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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