Reputation: 818
I am trying to achieve some set of calculations using R for calculating the norm of a point with a given coordinate and then take the maximum and then take the square out of it.
I have tried the following:
a <- c(-0.5,1)
b <- c(-1,-1.5)
c <- c(-1.5,1.5)
d <- c(1.5,-0.5)
e <- c(0.5,-0.5)
df <- data.frame(a,b,c,d,e)
In a more detailed way, this is what I want to perform:
I tried using the norm
and using the Frobenius
but I want to put everything into a function to be used later. Because manually when I create vectors for these tasks it becomes too tedious to calculate every point. Looking for an efficient/simpler way to perform this.
Upvotes: 1
Views: 409
Reputation: 887691
We loop across
the columns, get the square of the elements, sum
it, return with square root, get the max
and square it
library(dplyr)
df %>%
summarise(across(everything(), ~ sqrt(sum(.^2)))) %>%
max %>%
.^2
#[1] 4.5
In base R
, we can use
max(sqrt(colSums(df^2)))^2
#[1] 4.5
If we want to print
with all the digits, specify the digits
in print
print(max(sqrt(colSums(df^2)))^2, digits = 16)
#[1] 4.499999999999999
Upvotes: 2