R-我想遍历一个大矩阵的行并删除所有零 [英] R - I want to go through rows of a big matrix and remove all zeros

查看:402
本文介绍了R-我想遍历一个大矩阵的行并删除所有零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个非常大的矩阵(184 x 4000,键入double)中有很多行和列,我想删除所有0.矩阵中的值通常大于0,但有些行为0.0000.我尝试使用以下方法删除带有零的行:

I have a lot of rows and columns in a very large matrix (184 x 4000, type double), and I want to remove all 0's. The values in the matrix are usually greater than 0 but there are some rows of 0.0000 . I tried to remove the rows with zeros using this:

x <- x[which(rowSums(x) > 0),]

但是我剩下的只有184条记录中的3行.而且我知道,删除的181行并不全是0行. 有人知道为什么会发生这种情况以及如何解决吗?我在具有相同结构(184行,4000列)的不同矩阵上使用了相同的代码,并且可以正常工作.我想念什么?

but what I am left with is a mere 3 rows out of 184. And I know for a fact that the deleted 181 rows were not all 0 rows. Does anyone have a clue why this is happening and how I can fix it? I used this same code on a different matrix with the same structure (184 rows, 4000 columns) and it worked. What am I missing?

推荐答案

我终于有了答案.

x<- x[which(rowSums(x) > 0),]

仅返回184列中的3列是因为此函数只为您提供那些总和不为0和/或没有NA的行.我除了三行外,其他所有行中都有一些NA,我只是不知道. 仅仅取出NA不起作用,因为那不能解决rowSums问题. 我需要将NA视为零的函数,以便确实包含NA的行(除了3之外的所有行)也将被求和,而不仅仅是从矩阵中取出.所以我通过使用

only returned 3 rows out of 184 was because this function only gives you those rows that do not sum up to 0 and/or do not have an NA in them. And I had a few NA's in all but 3 rows, I just wasn't aware of. Simply taking out the NA's did not work, because that didn't solve the rowSums problem. I needed the function to treat my NA's as zeros, so that the rows that did entail NA's (as in all but 3) would also be summed up and not just taken out of the matrix. So I turned all NA's into zeros by using

x[is.na(x)] <- 0

,然后应用该函数对所有行进行求和,然后删除相加为0的行.它起作用了! 感谢大家的投入.尤其是@arkun!

and THEN applying the function to sum up all rows and remove the ones that add up to 0. And it worked! Thanks to everyone for your input. Especially @arkun!

这篇关于R-我想遍历一个大矩阵的行并删除所有零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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