[R] Utilizing column names to multiply over all columns

Sam Albers tonightsthenight at gmail.com
Tue Aug 16 22:50:20 CEST 2011


Thanks for the response David.

On Tue, Aug 16, 2011 at 1:13 PM, David Winsemius <dwinsemius at comcast.net> wrote:
>
> On Aug 16, 2011, at 3:37 PM, Sam Albers wrote:
>
>> ## Hello there,
>> ## I have an issue where I need to use the value of column names to
>> multiply with the individual values in a column and I have many
>> columns to do this over. I have data like this where the column names
>> are numbers:
>>
>> mydf <- data.frame(`2.72`=runif(20, 0, 125),
>>                 `3.2`=runif(20, 50, 75),
>>                 `3.78`=runif(20, 0, 100),
>>                 yy= head(letters,2), check.names=FALSE)
>
>> mydf
>        2.72      3.2      3.78 yy
> 1   31.07874 74.48555 89.306591  a
> 2  123.68290 74.30030 11.943576  b
> 3   89.64024 68.26378 97.627211  a
> 4   81.46604 59.79607 91.005217  b
>
>>
>> ## I had been doing something like this but this seems rather tedious
>> and clunky. These append the correct values to my dataframe but is
>> there any way that I can do this generally over each column, also
>> using each column name as the multiplier for that column?
>>
>> mydf$vd2.72 <- mydf$'2.72'*2.72
>> mydf$vd3.2 <- mydf$'3.2'*3.2
>> mydf$vd3.78 <- mydf$'3.78'*3.78
>>
>> ## So can I get to this point with a more generalized solution? For
>> now, I would also prefer to keep this in wide format and I am aware
>> (thanks to the list!) that I could use melt() to get the values I
>> want.
>
> You will get the warning that last last column is not "going right" but
> otherwise this returns what you asked for:
>
> sapply(1:length(mydf), function(i) mydf[[i]]* as.numeric(names(mydf)[i])  )

This suits my purposes well with a couple slight modifications:

## I made this into a data.frame so I could append it to the other one (mydf)
mydf.vd <- as.data.frame(sapply(1:length(mydf), function(i)
mydf[[i]]*as.numeric(names(mydf)[i]) ))

## I also renamed all the columns accordingly.
colnames(mydf.vd) <- paste("vd",names(mydf), sep="")

##Then added the new data.frame to the old one.
out <- cbind(mydf,mydf.vd)

Thanks for your help with this! (Also thanks Bert for the other
helpful suggestion)

>           [,1]     [,2]      [,3] [,4]
>  [1,]  84.53416 238.3538 337.57891   NA
>  [2,] 336.41748 237.7610  45.14672   NA
>  [3,] 243.82145 218.4441 369.03086   NA
>  [4,] 221.58762 191.3474 343.99972   NA
>  [5,]  81.78911 213.0770  97.90072   NA
> snipped remainder


>
> --
>
> David Winsemius, MD
> West Hartford, CT
>
>

Sam



More information about the R-help mailing list