[R] Creating new columns inside a loop

Thomas Lumley tlumley at u.washington.edu
Thu Aug 11 19:18:51 CEST 2005


On Thu, 11 Aug 2005, David L. Van Brunt, Ph.D. wrote:

> Ok, here's an english pseudo coded version of what I'd like to do...
>
> 10 columns of (somedata)
> names(somedata): C1 C2 C3 C4 C5
> Loop through each column
> FOR ColName = C1 through C5
> Compute a new column, named "ColNameA" = some result for each row
> Compute another new Column named ColNameB" = some other result for each row
> NEXTColName

A direct translation is

for(name in names(somedata)){
    somedata[[paste(name,"A",sep="")]]<-some.result(somedata[[name]])
    somedata[[paste(name,"B",sep="")]]<-some.other.result(somedata[[name]])
}

Possibly more efficient is

some.more.data <- lapply(somedata, some.result)
names(some.more.data)<-paste(names(somedata),"A",sep="")

yet.more.data <- lapply(somedata, some.other.result)
names(yet.more.data)<-paste(names(somedata),"B",sep="")

somedata<-cbind(somedata, some.more.data, yet.more.data)

 	-thomas


> Desired Result:
> Names(somedata): C1 C1A C1B C2 C2A C2B C3 C3A C3B C4 C4A C4B C5 C5A C5B
>
> So, basically, my question is how to both address and assign the names of
> the variables rather than the values of the variables while coding my loop.
> I hope that's clearer... kind of hard to explain!
>
> On 10 Aug 2005 21:55:01 +0200, Peter Dalgaard <p.dalgaard at biostat.ku.dk>
> wrote:
>>
>> "David L. Van Brunt, Ph.D." <dlvanbrunt at gmail.com> writes:
>>
>>> Ok, I know R isn't an optimal environment for looping (or so I've heard)
>> but
>>> I have a need to loop through columns of data and create new columns of
>> data
>>> based on calculations within rows...
>>>
>>> I'm sure there's a help file, but I'm not sure what search terms to use
>> to
>>> find it! The problem is that these new columns need to have names that I
>> can
>>> later access... Like NewVar1, NewVar2, etc....
>>>
>>> In php I'd call this "indirection" but I'm not sure what to call it in R
>> so
>>> that I can find instructions on how to create, name, and address the
>> values
>>> stored this way...
>>>
>>> any gentle nudges in the right direction would be greatly appreciated!
>>
>> A little more information about what you're actually trying to do and
>> I'm sure someone will give you a nudge with a sledgehammer...
>>
>> At present, your description is just that little bit too nebulous.
>>
>> --
>> O__ ---- Peter Dalgaard Øster Farimagsgade 5, Entr.B
>> c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
>> (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
>> ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
>>
>
>
>
> -- 
> ---------------------------------------
> David L. Van Brunt, Ph.D.
> mailto:dlvanbrunt at gmail.com
>
> 	[[alternative HTML version deleted]]
>
>

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle


More information about the R-help mailing list