vectorization - Vectorising an R function -
i have following function
f <- function(x){sum(g(x - x))} where
x - n-dimensional vector data g vecrtorized function how can vectorize function f take n-dimensional input , yield n-dimensional output?
i trying following
rowsums(sapply(x, "-", x)) the problem approach not cover case of one-dimensional x. possible cover both cases? example let
x <- c(1,2,3) x <- c(6,9,1) g <- function(x){x^2} if use sapply-based code correct answer (n-dimensional vector)
rowsums(sapply(x, "-", x)) [1] -12 -21 3 but if set x=1 , run same code, wrong answer (n-dimensional vector instead of scalar)
rowsums(sapply(x, "-", x)) [1] -5 -8 0 this not surprising, since rowsums applied column-vector gives column vector. need in case of one-dimensional x, apply sum. there elegant way without using if conditional on dimensions?
it seems have 2 examples, i've named them f , h:
x <- c(6,9,1) g <- function(x){x^2} f <- function(x){sapply(x,function(x)sum(g(x - x)))} f(1) # [1] 89 f(1:3) # [1] 89 66 49 h <- function(x){colsums(sapply(x,function(x) x-x))} h(1) # [1] -13 h(1:3) # [1] -13 -10 -7 it looked colsums looking there.
Comments
Post a Comment