Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will solve your example above

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...