[R] Delete rows from data.frame matching a certain criteria

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Thu Mar 1 18:59:29 CET 2012


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of mails
> Sent: Thursday, March 01, 2012 8:11 AM
> To: r-help at r-project.org
> Subject: [R] Delete rows from data.frame matching a certain criteria
> 
> Hello,
> 
> 
> consider the following data.frame:
> 
> test <- data.frame(n = c(1,2,3,4,5), v = c(6,5,7,5,3), pattern =
> c(1,1,NA,1,NA))
> 
> > test
>   n v pattern
> 1  1     6       1
> 2  2     5       1
> 3  3     7      NA
> 4  4     5       1
> 5  5     3      NA
> 
> 
> I tried to use apply and the adply function to set v to NA where
> pattern = 1
> and v to v where pattern = 1
> 
> 
> So basically the result should look like this:
> > test
>   n v pattern
> 1  1     NA       1
> 2  2     NA      1
> 3  3     7      NA
> 4  4     NA       1
> 5  5     3      NA
> 
> So far, I solved it by creating subsets and using merge but it turns
> out to
> be super slow. Is there a way to do that
> with the apply function?
> 
> Any help/hint is appreciated
> 
> Thanks
> 
> 

There is no need for apply here, this is a simple indexing problem.  Something like this should work

test$v <- ifelse(is.na(test$pattern), test$v, NA)


Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204




More information about the R-help mailing list