[R] Utilizing column names to multiply over all columns

Bert Gunter gunter.berton at gene.com
Tue Aug 16 22:30:05 CEST 2011


How about:

as.matrix(mydf[,1:3]) %*%  diag(as.numeric(names(mydf)[1:3]))

or

 scale(mydf[,1:3],1/as.numeric(names(mydf)[1:3])) ## ?scale

to create your new columns?

-- Bert

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])  )
>           [,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
>
> ______________________________________________
> 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.
>



-- 
"Men by nature long to get on to the ultimate truths, and will often
be impatient with elementary studies or fight shy of them. If it were
possible to reach the ultimate truths without the elementary studies
usually prefixed to them, these would not be preparatory studies but
superfluous diversions."

-- Maimonides (1135-1204)

Bert Gunter
Genentech Nonclinical Biostatistics



More information about the R-help mailing list