[R] Question related to merging zoo objects and apply function

Sergey Goriatchev sergeyg at gmail.com
Wed Jul 15 17:25:07 CEST 2009


Hello, Gabor

Generally, I follow the r-help rules and provide working code snippets
to illustrate the problem. In this case it was more methodological
question of how to loop names in merge() function.
I solved this very simply buy renaming specific columns after I have
ran merge().

Thank you for your time!

Best,
Sergey

On Wed, Jul 15, 2009 at 17:18, Gabor
Grothendieck<ggrothendieck at gmail.com> wrote:
> Please read the last line of every message to r-help.
> In particular simplify this as much as possible and
> construct some small artificial test data to illustrate.
>
> Anyways, func is probably not what you want.
> It has the same effect as
>
> func <- function(x, j) x[72+j] + [144+j]
>
> On Wed, Jul 15, 2009 at 9:26 AM, Sergey Goriatchev<sergeyg at gmail.com> wrote:
>> Hello everyone,
>>
>> Say I have defined a convenience function in my code like this:
>>
>> func <- function(x, j){
>>        x[168+j] <- x[72+j]+x[144+j]
>> }
>>
>> And now I apply it to some columns in a big zoo object like this:
>>
>>
>> for (m in 1:24){
>>        combined <- merge(combined, LA1sum=apply(combined, 1, func, j=m))
>> }
>>
>> output of this for-loop will be zoo object with columns named
>> LA1sum.1, LA1sum.2, ..., LA1.sum24.
>>
>> If I have a vector of names like this:
>>
>> namesVec <- c("LA1sum", "LP1sum", "GC1sum", "LL1sum", "LN1sum",
>> "SI1sum", "LX1sum", "CO1sum", "CL1sum", "QS1sum", "HO1sum",
>> "NG1sum", "XB1sum", "C.1sum", "FC1sum", "LH1sum", "LC1sum", "S.1sum",
>> "W.1sum", "KW1sum", "CC1sum", "KC1sum", "CT1sum", "SB1sum")
>>
>> What I want is in merge() for each m the name of new column to be one
>> of the elements in namesVec, that is
>> for m=1 I have LA1sum=apply(...,j=1)
>> for m=2 I have LP1sum=apply(...,j=2)
>> etc
>>
>> What it the way to do this?
>>
>> Thank you in advance for your help!
>>
>> Regards,
>> Sergey
>>
>> ______________________________________________
>> 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.
>>
>



-- 
I'm not young enough to know everything. /Oscar Wilde
Experience is one thing you can't get for nothing. /Oscar Wilde
When you are finished changing, you're finished. /Benjamin Franklin
Tell me and I forget, teach me and I remember, involve me and I learn.
/Benjamin Franklin
Luck is where preparation meets opportunity. /George Patten




More information about the R-help mailing list