[R] Recoding in R conditioned on a certain value.

David Winsemius dwinsemius at comcast.net
Sat Apr 5 22:18:44 CEST 2014

On Apr 5, 2014, at 9:51 AM, Kate Ignatius wrote:

> I'm trying to work out the average of a certain value by chromosome.
> I've done the following, but it doesn't seem to work:
> Say, I want to find average AD for chromosome 1 only and paste the
> value next to all the positions on chromosome 1:
> [sam$chrom == '1'] <-
> (sam$ad)/(colSums(sam[c(1:nrow(sam$chrom=='1'))],))

It "looks" wrong to me because of the mismatching lengths of the lhs and rhs but since you have not provided a test dataset that's all I will say.

The usual way to calculate a function within categorical groupings that will be "re-inserted" alongside the original dataframe is to use `ave`:

sam$mmad <- with( sam, ave(ad, chrom, FUN=mean) )

> I know this is convoluted and possible wrong... but I would like to do
> this for all chromosomes.
> Thanks!
David Winsemius
Alameda, CA, USA

More information about the R-help mailing list