r - multiply column by exponent in another column -



r - multiply column by exponent in another column -

a number in 1 column, exponent, k, m, b, ... in column. i'm trying product. i'm open improve way of doing this. problem in function. works when set in single value, not when given list.

exp <- function(val, exp){ switch(exp, k=1000 * val, k=1000*val, m = 1000000 * val, m=1000000 * val, b=1000000000 * val, b=1000000000*val, 0) } dat <- data.frame(x=c(1,2,3), val=c(3,4,0), exp=c('k','m','')) dat # x val exp #1 1 3 k #2 2 4 m #3 3 0 apply(dat[,c('val','exp')], 1, function(x) exp(x['val'], x['exp'])) #error in 1000 * val : non-numeric argument binary operator

you shouldn't using apply here:

dat$val1 <- exp_list[dat$exp] > dat x val exp val1 1 1 3 k 1e+03 2 2 4 m 1e+06 3 3 0 1e+03 > with(dat,val * val1) [1] 3e+03 4e+06 0e+00

the thing remember if 2d info construction info frame, apply wrong choice. note ?apply says first thing convert info frame matrix. if have mixed info types, coerced, in case character.

a simple vectorized solution preferable.

r apply

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -