R语言 查找向量的和、平均数和乘积

R语言 查找向量的和、平均数和乘积

在R语言中, sum(), mean(),prod() 方法是可用的,用于计算方法中指定的参数上的指定操作。如果指定了一个单一的向量,那么操作将在单个元素上执行,这相当于应用for循环。

使用的函数

  • mean()函数用于计算平均值。

语法: mean(x, na.rm)

参数

  • x: 数值向量
  • na.rm: 忽略NA值的布尔值
    • sum() 用于计算总和

语法: sum(x)

参数

  • x: 数值向量
    • prod() 用来计算乘积

语法: prod(x)

参数

  • x: 数值向量

下面的例子可以帮助你更好地理解。

例1 :

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

输出

[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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程