문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top