Re: [R] Listing Variables

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Fri 05 May 2006 - 06:46:57 EST

On 5/4/06, Farrel Buchinsky <fjbuch@gmail.com> wrote:
> bogdan romocea <br44114 <at> gmail.com> writes:
>
> >
> > Here's an example.
> > dfr <- data.frame(A1=1:10,A2=21:30,B1=31:40,B2=41:50)
> > vars <- colnames(dfr)
> > for (v in vars[grep("B",vars)]) print(mean(dfr[,v]))
>
> At first I did not know why you had bothered with the (dfr[,v])) part of the
> command. I thought you should have just as easily entered ... print(mean(v)).
> However, with a little help from David Clayton I discovered that one would
> simply be passing a string to the function rather than the underlying vector
> whose name is the string. Setting it up as you did makes sure that the vector
> is passed to the function.
>
> Armed with what I learnt from your response, I reasoned that I could roll
> everyting into an sapply and get everything coming out as a dataframe meanting
> that I could do the next step of the analysis.
> data.frame(sapply(dfr[,grep("B",names(dfr))],mean))
>
> sapply.dfr...grep..B...names.dfr.....mean.
> B1 35.5
> B2 45.5
>

Try this:

idx <- grep("Sepal", names(iris))
colMeans(iris[idx])
# or
data.frame(lapply(iris[idx], mean))



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Fri May 05 06:53:51 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 05 May 2006 - 08:10:01 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.