how to calculate the Euclidean norm of a vector in R?

Hanfei Sun picture Hanfei Sun · Jun 7, 2012 · Viewed 94.6k times · Source

I tried norm, but I think it gives the wrong result. (the norm of c(1, 2, 3) is sqrt(1*1+2*2+3*3), but it returns 6..

x1 <- 1:3
norm(x1)
# Error in norm(x1) : 'A' must be a numeric matrix
norm(as.matrix(x1))
# [1] 6
as.matrix(x1)
#      [,1]
# [1,]    1
# [2,]    2
# [3,]    3
norm(as.matrix(x1))
# [1] 6

Does anyone know what's the function to calculate the norm of a vector in R?

Answer

Bernd Elkemann picture Bernd Elkemann · Dec 10, 2014
norm(c(1,1), type="2")     # 1.414214
norm(c(1, 1, 1), type="2")  # 1.732051