使用ifelse从R中的数据集中删除不需要的行 [英] Using ifelse to remove unwanted rows from the dataset in R

查看:1032
本文介绍了使用ifelse从R中的数据集中删除不需要的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,我想在几个人的第一个观察年中删除第11个月的出现。是否有可能用ifelse做到这一点?类似于:

I have a dataset where I want to remove the occurences of month 11 in the first observation year for a couple of my individuals. Is it possible to do this with ifelse? Something like:

ifelse(ID=="1" & Month=="11" and Year=="2006", "remove these rows",  
  ifelse(ID=="2" & Month=="11" & Year=="2007", "remove these rows",   
         "nothing"))  

一如既往,所有帮助表示赞赏! :)

As always, all help appreciated! :)

推荐答案

你甚至不需要 ifelse()如果你想要的只是一个指示符,要删除与否。

You don't even need the ifelse() if all you want is an indicator of which to remove or not.

ind <- (Month == "11") &
           ((ID == "1" & Year == "2006") | (ID == "2" & Year == "2007"))

ind 如果月是11,如果其他两个子条款中的任何一个是 TRUE

ind will contain a TRUE if Month is "11" and if either of the other two subclauses is TRUE.

然后你可以通过 [或<在任何子集操作中使用!ind 删除这些样本code> subset()

Then you can drop those sample using !ind in any subset operation via [ or subset().

dat <- data.frame(ID = rep(c("1","2"), each = 72),
                  Year = rep(c("2006","2007","2008"), each = 24),
                  Month = rep(as.character(1:12), times = 3))
ind <- with(dat, (Month == "11") & ((ID == "1" & Year == "2006") |
                                    (ID == "2" & Year == "2007")))
ind
dat2 <- dat[!ind, ]

这给出了

R> ind
  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
 [13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
 [25] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [37] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [49] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [61] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [73] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [85] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [97] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
[109] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
[121] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[133] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
R>     dat2 <- dat[!ind, ]
R> nrow(dat)
[1] 144
R> nrow(dat2)
[1] 140

这在示例数据方面是正确的/

which is correct in terms of the example data/

这篇关于使用ifelse从R中的数据集中删除不需要的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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