user2424370
user2424370

Reputation:

R Programming Calculate Rows Average

How to use R to calculate row mean ?

Sample data:

enter image description here

f<- data.frame(
  name=c("apple","orange","banana"),
  day1sales=c(2,5,4),
  day1sales=c(2,8,6),
  day1sales=c(2,15,24),
  day1sales=c(22,51,13),
  day1sales=c(5,8,7)
)

Expected Results :

enter image description here

Subsequently the table will add more column for example the expected results is only until AverageSales day1sales.4. After running more data, it will add on to day1sales.6 and so on. So how can I count the average for all the rows?

Upvotes: 1

Views: 6229

Answers (2)

James King
James King

Reputation: 6355

rowMeans is the simplest way. Also the function apply will apply a function along the rows or columns of a data frame. In this case you want to apply the mean function to the rows:

f$AverageSales <- apply(f[, 2:length(f)], 1, mean)

(changed 6 to length(f) since you say you may add more columns).

will add an AverageSales column to the dataframe f with the value that you want

> f

##    name day1sales day1sales.1 day1sales.2 day1sales.3 day1sales.4 means
##1  apple         2           2           2          22           5   6.6
##2 orange         5           8          15          51           8  17.4
##3 banana         4           6          24          13           7  10.8

Upvotes: 2

Rich Scriven
Rich Scriven

Reputation: 99331

with rowMeans

> rowMeans(f[-1])
## [1]  6.6 17.4 10.8

You can also add another column to of means to the data set

> f$AvgSales <- rowMeans(f[-1])
> f
##     name day1sales day1sales.1 day1sales.2 day1sales.3 day1sales.4 AvgSales
## 1  apple         2           2           2          22           5      6.6
## 2 orange         5           8          15          51           8     17.4
## 3 banana         4           6          24          13           7     10.8

Upvotes: 3

Related Questions