在R中,为什么用空索引删除行或列导致空数据?或者,什么是'正确'的删除方式? [英] In R, why does deleting rows or cols by empty index results in empty data ? Or, what's the 'right' way to delete?
本文介绍了在R中,为什么用空索引删除行或列导致空数据?或者,什么是'正确'的删除方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是R中让我烦恼的事情之一。请考虑以下示例:
This is one of the things that really annoys me in R. Consider the following example:
a=data.frame(x=c(1,2),y=c(3,4))
i=which(a$x==0)
此时,我是整数(0),长度(i)是0.现在如果我这样做:
At this point, i is "integer(0)" and length(i) is 0. Now if I do:
b=a[-i,]
因为我用空索引删除,我希望b将所有数据都放在a中。但相反,b是一个空数据帧。我必须这样做:
Because I'm deleting by an empty index, I expect b to have all the data in a. But instead b is an empty data frame. I have to do this instead:
if (length(i)>0) b=a[-i,] else b=a
这同样适用于矩阵。有没有办法在没有if-else的情况下正确删除处理空索引?
The same applies to matrices too. Is there a way to delete that handles empty index correctly without the if-else on my part ?
推荐答案
这将解决你的例子上面
a <- data.frame(x=c(1,2),y=c(3,4))
b <- a[a$x != 0, ]
这篇关于在R中,为什么用空索引删除行或列导致空数据?或者,什么是'正确'的删除方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文