如何找到R数据框中所有值的平均值?
在本文中,我们将使用 mean()函数找到 R 中数据帧值的均值。
句法:
mean(dataframe)
创建数据框
可以使用 R 库中预定义的 data.frame()函数创建数据帧。此函数接受要创建的数据框所需的元素以及行数和列数。
以下是用于创建数据框的 R 程序:
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)
R
mean1 = mean(df)
print(mean1)
R
# Converting dataframe to matrixa
as.matrix(df)
R
# Finding mean of the dataframe
# Using mean() function
mean(as.matrix(df))
R
# 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)
R
# Computing mean of the above dataframe
# Using the mean() function
mean(as.matrix(df))
R
# 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)
R
# Computing mean of the dataframe
# Using mean() function
mean(as.matrix(df))
输出:
row1 row2 row3
1 0 3 6
2 1 4 7
3 2 5 8
数据帧的计算平均值
R 语言提供了一个内置函数mean() 来计算数据帧的平均值。下面是一个用于实现 mean() 的 R 程序。
电阻
mean1 = mean(df)
print(mean1)
输出:
在上面的代码中,显示了一条警告消息,它返回 NA,因为数据框不是数字形式。需要将其转换为矩阵形式来计算数据帧的均值。 R 提供了一个内置的 as.matrix()函数来将数据帧转换为矩阵。
电阻
# Converting dataframe to matrixa
as.matrix(df)
输出:
现在,要计算从数据帧创建的这个矩阵的均值,请在矩阵上使用均值函数。
电阻
# Finding mean of the dataframe
# Using mean() function
mean(as.matrix(df))
输出:
4
示例 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)
输出:
电阻
# Computing mean of the above dataframe
# Using the mean() function
mean(as.matrix(df))
输出:
37.5555555555556
示例 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)
输出:
电阻
# Computing mean of the dataframe
# Using mean() function
mean(as.matrix(df))
输出:
21681.2222222222