Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mean of a column in a data frame, given the column's name

Tags:

r

mean

I'm inside a big function I have to write. In the last part I have to calculate the mean of a column in a data frame. The name of the column I am operating on is given as an argument to the function.

like image 757
FranGoitia Avatar asked Apr 18 '14 23:04

FranGoitia


3 Answers

I think you're asking how to compute the mean of a variable in a data frame, given the name of the column. There are two typical approaches to doing this, one indexing with [[ and the other indexing with [:

data(iris)
mean(iris[["Petal.Length"]])
# [1] 3.758
mean(iris[,"Petal.Length"])
# [1] 3.758
mean(iris[["Sepal.Width"]])
# [1] 3.057333
mean(iris[,"Sepal.Width"])
# [1] 3.057333
like image 149
josliber Avatar answered Nov 15 '22 06:11

josliber


if your column contain any value that you want to neglect. it will help you

## da is data frame & Ozone is column name 

##for single column
mean(da$Ozone, na.rm = TRUE)  

##for all columns
colMeans(x=da, na.rm = TRUE)
like image 35
reza.cse08 Avatar answered Nov 15 '22 06:11

reza.cse08


Any of the following should work!!

df <- data.frame(x=1:3,y=4:6)

mean(df$x)
mean(df[,1])
mean(df[["x"]])
like image 30
Shambho Avatar answered Nov 15 '22 06:11

Shambho