In R, why does deleting rows or cols by empty index results in empty data ? Or, what's the 'right' way to delete?

元气小坏坏 提交于 2019-12-25 03:22:16

问题


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)

At this point, i is "integer(0)" and length(i) is 0. Now if I do:

b=a[-i,]

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

The same applies to matrices too. Is there a way to delete that handles empty index correctly without the if-else on my part ?


回答1:


This will solve your example above

 a <- data.frame(x=c(1,2),y=c(3,4))
 b <- a[a$x != 0, ]


来源:https://stackoverflow.com/questions/28798401/in-r-why-does-deleting-rows-or-cols-by-empty-index-results-in-empty-data-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!