R Programming Calculate Rows Average

痞子三分冷 提交于 2019-12-11 06:04:35

问题


How to use R to calculate row mean ?

Sample data:

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 :

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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/23556309/r-programming-calculate-rows-average

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!