[R] Utilizing column names to multiply over all columns

Sam Albers tonightsthenight at gmail.com
Tue Aug 16 21:37:35 CEST 2011


## 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)

## 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.
mydf

## Thanks so much in advance!

Sam



More information about the R-help mailing list