Creating the mean average of every nth object in a specific column of a dataframe

社会主义新天地 提交于 2019-12-02 10:10:25

Just use a combination of rowMeans and subsetting. So something like:

n = 5
rowMeans(data[seq(1, nrow(data), n),])

Alternatively, you could use apply

## rowMeans is better, but 
## if you wanted to calculate the median (say)
## Just change mean to median below
apply(data[seq(1, nrow(data), n),], 1, mean)

If the question is how to reproduce h_average but without the loop then

1) colMeans Try this:

# assume inDf and h_average as defined in the question

tstep <- 24
h <- x <- 1

h_average(inDf, tstep, h, x)
##       s1 
## 49299.09 

# same but without loop
colMeans(inDf[seq(h, nrow(inDf), tstep), x, drop = FALSE])
##       s1 
## 49299.09 

This also works if x is a vector of column numbers, e.g. x = 1:2.

1a) This variation works too:

colMeans(inDf[seq_len(tstep) == h, x, drop = FALSE])

2) aggregate Another possibility is this:

aggregate(DF[x], list(h = gl(tstep, 1, nrow(inDf))), mean)[h, ]

which has the advantage that both x and h may be vectors, e.g.

x <- 1:2
h <- 1:3

DF <- as.data.frame(inDF)
aggregate(DF[x], list(h = gl(tstep, 1, nrow(inDf))), mean)[h, ]
##   h       s1       s2
## 1 1 49299.09 4964.277
## 2 2 49661.34 5177.910
## 3 3 49876.77 4946.447

To get all h then use h <- 1:tstep or just omit [h, ].

Note: InDf as defined in the question is a matrix and not a data frame as its name seems to suggest.

Update Some improvements in (1) and added (1a) and (2).

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