How to calculate the average of a column in R?

Asked

Viewed 19,175 times

4

I have an Excel file in format .csv(comma separated values) and I want to read what is in a column, add and calculate its average.

How to open the file I already know, but I don’t know how to add the values to calculate the average.

From now on, I thank you for your help.

  • 3

    -1. It is necessary to demonstrate some research effort on the subject that wants to be clarified. It is a basic principle of the OS.

3 answers

6

Extending the answer from @Raphael Nishimura:

If the goal is to average all the columns of the date.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 that all columns of dados are of the type numeric):

apply(dados,2,mean)

Where 2 indicates that the data.frame will be divided into columns (1 for lines and c(1,2) for rows AND columns). Note that you can replace the function mean by any other you wish, such as sd to calculate the standard deviation.

6


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

sum(dados$V1)

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

mean(x = dados$V1)

0

If you want to calculate the average of all columns, you can use:

colMeans(dados)

If you want to average a specific column

colMeans(dados$V1)

It is also possible to calculate the average of the lines:

rowMeans(dados); rowMeans(dados$V1)

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.