R sqrt() Function - Calculate Square Root
The R sqrt() function is used to calculate the square root of a numeric value.
Square root is a mathematical concept. The square root of a non-negative number, when squared, equals the original number. In statistics, calculating the standard deviation requires the use of sqrt().
The syntax of the sqrt() function is as follows:
sqrt(x)
Parameter description:
xInput a numeric value or numeric vector; it must be non-negative (negative numbers return NaN).
Example
# Calculate the square root of a single numeric value
print(sqrt(16))
print(sqrt(2))
# Calculate the square root of each element in the vector
x <- c(4, 9, 16, 25, 36)
result.sqrt <- sqrt(x)
print(result.sqrt)
print(sqrt(16))
print(sqrt(2))
# Calculate the square root of each element in the vector
x <- c(4, 9, 16, 25, 36)
result.sqrt <- sqrt(x)
print(result.sqrt)
Executing the above code produces the following output:
[1] 4 [1] 1.414214 [1] 2 3 4 5 6
sqrt() is often used in scenarios such as calculating standard deviation, Euclidean distance, etc.:
Example
# Manually calculate the standard deviation
x <- c(2, 4, 6, 8, 10)
# Step 1: Calculate the mean
m <- mean(x)
# Step 2: Calculate the variance (mean of squared deviations)
variance <- sum((x - m)^2) / (length(x) - 1)
# Step 3: Standard deviation = square root of variance
std_dev <- sqrt(variance)
print(paste("Manual standard deviation:", std_dev))
# Compare with the sd() function
print(paste("sd() function:", sd(x)))
x <- c(2, 4, 6, 8, 10)
# Step 1: Calculate the mean
m <- mean(x)
# Step 2: Calculate the variance (mean of squared deviations)
variance <- sum((x - m)^2) / (length(x) - 1)
# Step 3: Standard deviation = square root of variance
std_dev <- sqrt(variance)
print(paste("Manual standard deviation:", std_dev))
# Compare with the sd() function
print(paste("sd() function:", sd(x)))
Executing the above code produces the following output:
[1] "手动标准差: 3.16227766016838" [1] "sd() 函数: 3.16227766016838"Other Extensions
R Language Examples