[R] Conditional sampling?

Olga Lyashevska olga at herenstraat.nl
Tue Feb 9 17:41:31 CET 2010


Hello all,

Here is my solution, in case someone else needs it.

> I have a dataframe consisting of two columns.
>
>> col1<-factor(c("a","a","b","b","c","c"))
>> col2<-factor(c("a","b","c","d","e","f"))
>> somedf<-data.frame(col1,col2)
>> somedf
>     col1   col2
> 1      a      d
> 2      a      e
> 3      b      f
> 4      b      g
> 5      c      h
> 6      c      i
>
>> sample(col1,2,replace=T)
> [1] b c
> Levels: a b c
>
> Now I want to sample from col2, but I want to restrict a vector I am
> going to sample from to only those elements that correspond to col1  
> That
> is, I want to take a sample from f, g, h, i.  Elements corresponding  
> to
> level a need to be dropped.
>
>    col1    col2
>
> 3      b      f
> 4      b      g
> 5      c      h
> 6      c      i
>


s <- sample(col1,2,replace=T)
col2[col1 %in% s]

Cheers,
Olga



More information about the R-help mailing list