[R] Remove specific rows in a matrix/data.frame

jim holtman jholtman at gmail.com
Thu Oct 13 18:56:24 CEST 2011


try this:

> x <- read.table(textConnection("Letter Number
+ a 1
+ a 1
+ b 1
+ b 0
+ c 0
+ c 1
+ d 0
+ d 0"), as.is = TRUE, header = TRUE)
> closeAllConnections()
> # following assumes that there are pairs of numbers
> result <- do.call(rbind, lapply(split(x, x$Letter), function(.pair){
+     if (all(.pair$Number[1L] == .pair$Number)) return(.pair[1L, ])
+     is1 <- which(.pair$Number == 1)
+     if (length(is1) == 1) return(.pair[is1, ])
+     else return(NULL)
+ }))
>
> result
  Letter Number
a      a      1
b      b      1
c      c      1
d      d      0
>


On Thu, Oct 13, 2011 at 12:42 PM, syrvn <mentor_ at gmx.net> wrote:
> Hi,
>
>
> imagine the following matrix/data.frame
>
> Letter Number
> a 1
> a 1
> b 1
> b 0
> c 0
> c 1
> d 0
> d 0
>
> If the numbers for two identical letters are also identical then I want to
> remove either the first or the
> second row of that letter. If for a letter the numbers are 1 and 0 I want to
> remove the row with the 0.
>
> That means if the code works I would and up with the following
> matrix/data.frame
>
> Letter Number
> a 1
> b 1
> c 1
> d 1
>
>
> Many thanks,
> Syrvn
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Remove-specific-rows-in-a-matrix-data-frame-tp3902149p3902149.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list