R语言 如何找到R数据框中所有数值的平均值

R语言 如何找到R数据框中所有数值的平均值

在这篇文章中,我们将使用mean()函数来查找R数据框架中所有数值的平均值。

语法

mean(dataframe)

创建一个数据框架

可以使用R库中预定义的data.frame()函数来创建一个数据框架。这个函数接受要创建的数据框架所需的元素以及行和列的数量。

下面是一个创建数据框架的R程序。

# R Program to create a dataframe
  
# Creating a Data Frame 
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8) 
print(df)
Bash

输出

  row1 row2 row3
1    0    3    6
2    1    4    7
3    2    5    8
Bash

计算数据框的平均数

R语言提供了一个内置的函数mean()来计算数据框架的平均值。下面是一个实现mean()的R程序。

mean1 = mean(df)
print(mean1)
Bash

输出

如何找到R数据框中所有数值的平均值?

在上面的代码中,显示了一条警告信息,因为数据框架不是数字形式的,所以返回NA。需要将其转换为矩阵形式以计算数据帧的平均值。R提供了一个内置的as.matrix()函数来将数据框架转换为矩阵。

# Converting dataframe to matrixa
as.matrix(df)
Bash

输出

如何找到R数据框中所有数值的平均值?

现在,为了计算这个由数据框架创建的矩阵的平均值,在矩阵上使用平均值函数。

# Finding mean of the dataframe
  
# Using mean() function
mean(as.matrix(df))
Bash

输出

4
Bash

例2 :

# R program to illustrate dataframe 
Roll_num = c(01, 02, 03)
Age = c(22, 25, 45)
Marks = c(70, 80, 90)
    
# To create dataframe use data.frame command and 
# then pass each of the vectors  
# we have created as arguments 
# to the function data.frame() 
df = data.frame(Roll_num, Age, Marks) 
    
print(df)
Bash

输出

如何找到R数据框中所有数值的平均值?

# Computing mean of the above dataframe
  
# Using the mean() function
mean(as.matrix(df))
Bash

输出

37.5555555555556
Bash

例3 :

# R program to illustrate dataframe 
ID = c(01, 02, 03)
Age = c(25, 30, 70)
Salary = c(70000, 85000, 40000)
    
# To create dataframe use data.frame command and 
# then pass each of the vectors  
# we have created as arguments 
# to the function data.frame() 
df = data.frame(ID, Age, Salary) 
    
print(df)
Bash

输出

如何找到R数据框中所有数值的平均值?

# Computing mean of the dataframe
  
# Using mean() function
mean(as.matrix(df))
Bash

输出

21681.2222222222
Bash

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册