[R] Means from selected columns in a data frame

David Winsemius dwinsemius at comcast.net
Tue Jul 20 15:33:42 CEST 2010


On Jul 20, 2010, at 9:25 AM, David Winsemius wrote:

>
> On Jul 20, 2010, at 9:13 AM, Marcus Drescher wrote:
>
>> Hi all,
>>
>> I have a dataframe with survey data. Now I want to calculate means  
>> from several but not all columns (e.g. a1, a2, a3) and save them in  
>> a new separate column (e.g. a).
>
> Well that would be possible unless you are in Minitab or Excel where  
> you
                ^not^
> can put stuff of variable length where ever.
But I probably misunderstood your intent, anyway
>>
>> Like: a = mean(a1, a2, a3)
>>
>> Can someone help me or give me the right key word to look for?
>
> ?colMeans
>
> Perhaps:
> meansvec <- colMeans()
>
> If on the other hand, you wanted rowMeans (since your problems  
> specification was rather ambiguous)  that function is also available.
>
I suppsoe your request that these results be put in another column may  
have meant you wanted row means and therefore you could try:

dfrm$a_mns <- rowMeans( dfrm[ , c("a1", "a2", "a3")] )

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list