[R] help with algorithm

r student studentofr at gmail.com
Mon Aug 1 00:38:29 CEST 2011


Thanks for everyone's suggestions.  I think looping is the way to go.

I have 50 files on which I need to apply the same procedures, so I'll
try and wrap my final code in some sort of loop.

> > highest and lowest groups)?  (I can do this in multiple steps* but wonder
> > what the best, "R way" is to do this.)
>
> Here is one way to get the means by groups:
>
> tmp <- with(mtcars, tapply(mpg, cyl, mean))
> ## and now subset by it
> subset(mtcars, mtcars$cyl %in% names(c(which.max(tmp), which.min(tmp))))

Looks exactly like what I'd need but, I tried and got a list of
variable names followed by "<0 rows> (or 0-length row.names)".

If I can get this to work, would I be able to use it for weighted
means with "rm.na=TRUE"?


Since they're weighted means I've been trying to use the following:

f<-by(oh,oh$BYGRP, function(z) weighted.mean(z$VAR1,z$WEIGHT,na.rm=TRUE))

Which seems to work, but need to use these means to subset the highest
and lowest groups (to create density plots of).  The above produces an
object that I'm not entirely sure how to work with (say to merge back
onto "oh" so I can subset.



> How to draw cutoff lines at specific points on density plots?

> plot(density(rnorm(100)))
> abline(v = c(-1, 1))


Thanks!  Amazing how much easier to do this in R than in SAS.


> > How to create a matrix of plots?  (Take 4 separate plots and put them into a
> > single graphic.)
>
> This depends a bit on the potential complexity of layouts you need.
> See ?par and ?layout

Thanks again!  Many good suggestions here and from others.

> > * Get group means, add means back to file, sort by mean, take first and last
> > groups
>
> dat <- mtcars
> dat$gm <- with(mtcars, ave(mpg, cyl, FUN = mean))

I tried, but I think the NAs are giving me trouble.

tmp <- oh
tmp$GM <- with(oh, ave(FINCP, PUMA, FUN=mean))
summary(tmp$GM)
       Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's
                                                                          114222

And I need to create weighted means anyway.

> Hope this helps,
>
> Josh
> --
> Joshua Wiley
> Ph.D. Student, Health Psychology
> Programmer Analyst II, ATS Statistical Consulting Group
> University of California, Los Angeles
> https://joshuawiley.com/


Very helpful.  Thanks.



More information about the R-help mailing list