[R] Listing Variables

Gabor Grothendieck ggrothendieck at gmail.com
Thu May 4 22:46:57 CEST 2006


On 5/4/06, Farrel Buchinsky <fjbuch at 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))




More information about the R-help mailing list