在 R 中查找向量的总和、均值和乘积
R 中提供 sum()、mean()和prod()方法,用于计算对方法中指定参数的指定操作。如果指定了单个向量,则对单个元素执行操作,这相当于 for 循环的应用。
函数:
- mean()函数用于计算均值
Syntax: mean(x, na.rm)
Parameters:
- x: Numeric Vector
- na.rm: Boolean value to ignore NA value
- sum() 用于计算总和
Syntax: sum(x)
Parameters:
- x: Numeric Vector
- prod() 用于计算乘积
Syntax: prod(x)
Parameters:
- x: Numeric Vector
下面给出的示例可以帮助您更好地理解。
示例 1:
R
vec = c(1, 2, 3 , 4)
print("Sum of the vector:")
# inbuilt sum method
print(sum(vec))
# using inbuilt mean method
print("Mean of the vector:")
print(mean(vec))
# using inbuilt product method
print("Product of the vector:")
print(prod(vec))
R
vec = c(1.1, 2, 3.0 )
print("Sum of the vector:")
# inbuilt sum method
print(sum(vec))
# using inbuilt mean method
print("Mean of the vector:")
print(mean(vec))
# using inbuilt product method
print("Product of the vector:")
print(prod(vec))
R
# declaring a vector
vec = c(1.1,NA, 2, 3.0,NA )
print("Sum of the vector:")
# inbuilt sum method
print(sum(vec))
# using inbuilt mean method
print("Mean of the vector with NaN values:")
# not ignoring NaN values
print(mean(vec))
# ignoring missing values
print("Mean of the vector without NaN values:")
print(mean(vec,na.rm = TRUE))
# using inbuilt product method
print("Product of the vector:")
print(prod(vec))
输出
[1] “Sum of the vector:”
[1] 10
[1] “Mean of the vector:”
[1] 2.5
[1] “Product of the vector:”
[1] 24
示例 2:
电阻
vec = c(1.1, 2, 3.0 )
print("Sum of the vector:")
# inbuilt sum method
print(sum(vec))
# using inbuilt mean method
print("Mean of the vector:")
print(mean(vec))
# using inbuilt product method
print("Product of the vector:")
print(prod(vec))
输出
[1] “Sum of the vector:”
[1] 6.1
[1] “Mean of the vector:”
[1] 2.033333
[1] “Product of the vector:”
[1] 6.6
示例 3:具有 NaN 值的向量
电阻
# declaring a vector
vec = c(1.1,NA, 2, 3.0,NA )
print("Sum of the vector:")
# inbuilt sum method
print(sum(vec))
# using inbuilt mean method
print("Mean of the vector with NaN values:")
# not ignoring NaN values
print(mean(vec))
# ignoring missing values
print("Mean of the vector without NaN values:")
print(mean(vec,na.rm = TRUE))
# using inbuilt product method
print("Product of the vector:")
print(prod(vec))
输出
[1] “Sum of the vector:”
[1] NA
[1] “Mean of the vector with NaN values:”
[1] NA
[1] “Mean of the vector without NaN values:”
[1] 2.033333
[1] “Product of the vector:”
[1] NA