Message-ID: <03614043-DBDD-4215-8A78-D565F622BCAD@comcast.net>
Date: 2015-05-15T20:11:54Z
From: David Winsemius
Subject: print dataframe names in loop
In-Reply-To: <CAHOWgNXo+Tz_0KfGqY9R95NBDEuk_PTCGvW-S4n00xVJmG+DFQ@mail.gmail.com>
On May 15, 2015, at 10:05 AM, Kai Mx wrote:
> thanks, that would work, but isn't there a maybe more elegant way to
> "extract" the name from the df variable within the current for (df in
> list()) loop?
>
You do realize that the `for` function returns NULL, I hope? I was surprised when I learned this, although it is clearly stated in the help page.
Neither `lapply` nor `for` passes the names into the environment for evaluation:
for( d in dflist ) { z <- deparse(substitute(d)); print(z)}
[1] "d"
[1] "d"
[1] "d"
People would generally use this approach:
for (n in names(dflist) { ...do something with nm or dflist[[nm]]... }
--
David.
> Best,
>
> Kai
>
>
> On Fri, May 15, 2015 at 2:20 PM, Jim Lemon <drjimlemon at gmail.com> wrote:
>
>> Hi Kai,
>> One way is to name the components of your list with the names of the
>> data frames:
>>
>> df1<-data.frame(a=1:3)
>> df2<-data.frame(a=4:6)
>> df3<-data.frame(a=7:9)
>> dflist<-list(df1,df2,df3)
>> names(dflist)<-c("df1","df2","df3")
>> for(i in 1:length(dflist)) cat(names(dflist)[i],"\n")
>> df1
>> df2
>> df3
>>
>> Jim
>>
>>
>> On Fri, May 15, 2015 at 10:05 PM, Kai Mx <govokai at gmail.com> wrote:
>>> Hi everybody,
>>>
>>> I just can't figure this out:
>>>
>>> I have a loop trough several dataframes such as
>>>
>>> for (df in list(df1, df2, df3, ...)) {
>>> ..some functions with df..
>>> }
>>>
>>> now I want to print out the current dataframes name (ie the list items
>>> name) with the cat command before the actual functions to have better
>>> orientation in the output.
>>> However, I haven't been successful with different variations of
>> deparse(),
>>> substitute(), (cat(substitute(df)) gives me 'df' for the whole loop).
>>>
>>> Could somebody please enlighten me?
>>>
>>> Thanks so much!
>>>
>>> Best,
>>>
>>> Kai
--
David Winsemius
Alameda, CA, USA