How to calculate the average of a column in R?

3

I have an Excel file in the format .csv (comma-separated values) and I want to read what's in a column, add and calculate its mean.

How to open the file I already know, but I do not know how to add the values to calculate the average.

Thanks in advance for your help.

    
asked by anonymous 13.12.2014 / 20:20

2 answers

5
Assuming that the data frame you read from the Excel file is in an object called dados and that you want to sum the values of a column / variable of that date frame called V1 , just use the function sum() :

sum(dados$V1)

In addition, you can calculate the mean of the values of this column / variable directly using the mean(x) function:

mean(x = dados$V1)
    
14.12.2014 / 00:23
5

Extending @Raphael Nishimura's response:

If the goal is to calculate the average of all columns of data.frame dados , instead of using a command for each of the columns as in:

mean(dados$V1)
mean(dados$V2)
mean(dados$V3)
...

use the function apply (assuming all columns of dados are of type numeric ):

apply(dados,2,mean)

Where 2 indicates that the data.frame will be divided into columns ( 1 to rows and c(1,2) to rows and columns). Note that you can replace the mean function with another one you want, such as sd to calculate the standard deviation.

    
16.12.2014 / 12:18