[R] subsetting matrix according to columns with character index

Henrique Dallazuanna wwwhsd at gmail.com
Wed Aug 13 20:11:55 CEST 2008


Try this:

x
  V1 V2 V3
1 a1 c1  1
2 a1 c1  2
3 a2 c1  1
4 a1 c2  1
5 a1 c2  2


lis <- split(x, list(x$V1, x$V2), drop = TRUE)
do.call(rbind, unname(lis[sapply(lis, function(x)all(1:2 %in% x[,3]))]))

On Wed, Aug 13, 2008 at 3:00 PM, Ralph S. <ruffel1 at hotmail.com> wrote:
>
>  Hi,
>
> I have a long matrix of the following form which I would like to subset according to the third column:
>
> [x y z]:
>
> a1 c1 1
> a1 c1 2
> a2 c1 1
> a1 c2 1
> a1 c2 2
> . . .
>
>
> The first two columns a characters ai and cj.
>
> I would like to keep all the rows where there are two entries for z, 1 and 2.
>
> That is, I want:
> a1 c1 1
> a1 c1 2
> a1 c2 1
> a1 c2 2
> . . .
>
> I try to use something like df[by(df,c(df$x,df$y),sum(z)==3),] but that only gives me one line of data per x y combination.
>
> Is there an easy way of coding to keep all rows for a and c combinations where z has entries both 1 and 2?
>
> Many thanks,
>
> Ralph
>
> _________________________________________________________________
>
>
> LM_WLYIA_whichathlete_us
> ______________________________________________
> 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.
>



-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O



More information about the R-help mailing list