[R] Conditional Loop For Data Frame Columns

David Winsemius dwinsemius at comcast.net
Mon Jan 9 06:17:04 CET 2012


On Jan 9, 2012, at 12:02 AM, jawbonemurphy wrote:

> Hi Dave,
>
> Thanks for your response!
>
> I'm new at R, and I'm afraid I'm not sure what you mean by:
>
> ?lapply
> ?"["
> ?order

It means I thought you might get the answers you needed by looking at  
those functions' help pages.

>
> Were these suggestions for other commands to try?  If so, can you be  
> more
> specific?  I apologize for being clueless :)

You should not apologize for being clueless but you should apologize  
for not providing a sample dataset that would illustrate what you were  
working with. This is probably because you did not read the Posting  
Guide which you should take the time to do before responding. The  
example doesn't need to be big but it should have all columns in the  
format of the objects you are currently working with, and they should  
be created with code or reproducible. Just printing out the dataframe  
or head(dfrm) will NOT be as useful as if you posted the output of :

dput(head(dfrm,20))

# assuming that 20 rows is sufficient to have enough of any grouping  
variables you need to form some groups. If not then you can increase  
the size.
>
> Secondly, you're right that the script I have now leaves me with the  
> means
> from the last column.  Do you have any suggestions for how to write  
> the
> results for each "i" to a unique vector?  I was going to try:

If you pre-allocated an objec that was large enought or if you used a  
list, you could add items with "[" and hte index on the LHS of the  
assignment.
>
> mean_i <- tapply(x[,i], ID, etc..., but I was thinking that this  
> would just
> create a vector named "mean_i" w/ results of last column, not a  
> separate
> vector for each "i".

tapply does not create a vector. It creates a matrix or a list. And  
that has the same problem ... you are overwriting with each pass  
through the loop.

> I guess what I want is some command to print the
> result of each run before repeating with the next "i".  Any ideas?

?print   # but is that what you really wanted? Only console output?

>  Again,
> thanks for the help.
>
> Best,
> Logan
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Conditional-Loop-For-Data-Frame-Columns-tp4276821p4277615.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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list