R:如何删除data.frame中的某些行 [英] R: how to remove certain rows in data.frame

查看:56
本文介绍了R:如何删除data.frame中的某些行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

> data = data.frame(a = c(100, -99, 322, 155, 256), b = c(23, 11, 25, 25, -999))
> data
    a    b
1 100   23
2 -99   11
3 322   25
4 155   25
5 256 -999

对于这样的 data.frame,我想删除包含 -99 或 -999 的任何行.所以我生成的 data.frame 应该只包含第 1、3 和 4 行.

For such a data.frame I would like to remove any row that contains -99 or -999. So my resulting data.frame should only consist of rows 1, 3, and 4.

我正在考虑为此编写一个循环,但我希望有一种更简单的方法.(如果我的 data.frame 包含 a-z 列,那么循环方法将非常笨拙).我的循环可能看起来像这样

I was thinking of writing a loop for this, but I am hoping there's an easier way. (If my data.frame were to have columns a-z, then the loop method would be very clunky). My loop would probably look something like this

i = 1
for(i in 1:nrow(data)){
  if(data$a[i] < 0){
    data = data[-i,]
  }else if(data$b[i] < 0){
    data = data[-i,]
  }else data = data
}

推荐答案

也许这个:

ind <- Reduce(`|`,lapply(data,function(x) x %in% c(-99,-999)))
> data[!ind,]
    a  b
1 100 23
3 322 25
4 155 25

这篇关于R:如何删除data.frame中的某些行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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