如何在R中找到平均值
时间:2020-02-23 14:43:49 来源:igfitidea点击:
在统计数据中,均值定义为将所有值相加并除以值总数后得到的"平均值"值。
本教程着重于使用三种不同的方法查找值的平均值。
查找输入值列表的平均值
在这种方法中,我们正在创建一个包含一些值的列表,并尝试查找这些值的平均值。
例子1
x <- c(21,32,43,54,65,76,87,98) #calculates the mean for the given values mean(x) Output --> 59.5
在上面的代码中,我们首先创建了包含某些值的列表" x"。
然后,借助mean()函数,我们可以在列表" x"中找到值的平均值。
例子2
x <- c(2.5,3.7,6.8,5.7,6.8,4.6) #calculates the mean for the decimal values mean(x) --> 5.016667
在文本文件中查找值的平均值
通过这种方法,您将了解如何找到存储在文本文件中的值的平均值。
x <- read.table('testvalues.txt') #This will read the text file
mean(x$V1) #This will calculate the mean of the values in the text file --> 75.33333
查找存储在CSV文件中的值的平均值
在这种方法中,我们要导入一个CSV文件,其中包含一些值。
然后,与上述步骤一样,可以使用mean()函数找到值的均值。
下面的代码演示了CSV文件的导入和读取。
x <- read.csv('testdata1.csv')
上图显示了CSV文件中存在的值。
在下一步中,我们可以计算这些值的平均值。
为此,请运行以下代码。
mean(x$Values) #calculates the mean for the values present in CSV file --> 68.92857