[R] Utilizing column names to multiply over all columns
Hadley Wickham
hadley at rice.edu
Tue Aug 16 23:12:38 CEST 2011
>> 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]) ))
You can simplify this a little with the sweep function:
sweep(mydf[, 1:3], 2, as.numeric(names(mydf)[1:3]), "*")
Hadley
--
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/
More information about the R-help
mailing list