📜  在 R 中查找向量的总和、均值和乘积

📅  最后修改于: 2022-05-13 01:55:27.424000             🧑  作者: Mango

在 R 中查找向量的总和、均值和乘积

R 中提供 sum()、mean()prod()方法,用于计算对方法中指定参数的指定操作。如果指定了单个向量,则对单个元素执行操作,这相当于 for 循环的应用。

函数:

  • mean()函数用于计算均值
  • sum() 用于计算总和
  • prod() 用于计算乘积

下面给出的示例可以帮助您更好地理解。

示例 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))


输出



示例 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))

输出

示例 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))

输出