Fred - 5 months ago 29

R Question

I have a dataframe of which I put one variable into a vector.

From this vector, I would like to calculate for every 5 values

`mean`

`min`

`max`

I have managed to calculate the means in this way:

`means <- colMeans(matrix(df$values, nrow=5))`

I know I can calculate the min and max like this:

`max <- max(df$values[1:5])`

min <- min(df$values[1:5])

How do I repeat this for

Aditionally, how can I get statistic and p-value from a 1-sample t-test for each n-row?

Answer Source

You can use `sapply`

and `split`

for this:

```
sapply(split(df$value, rep(1:(nrow(df)/5), each=5)), mean)
sapply(split(df$value, rep(1:(nrow(df)/5), each=5)), min)
sapply(split(df$value, rep(1:(nrow(df)/5), each=5)), max)
```

If you want the outputs in a matrix you can use what @lmo proposed in the comments:

```
sapply(split(df$value, rep(1:(nrow(df)/5), each=5)),
function(x) c(mean=mean(x), min=min(x), max=max(x)))
```

** How to get statistic and p-value from a sample t-test for each n-row:** This would be a bit harder to implement. Look below;

```
#mu=3 for sample t-test
t_test_list <- sapply(split(df$value, rep(1:(nrow(df)/5), each=5)), t.test, mu=3)
p_value_list <- lapply(as.data.frame(t_test_list),function(x) x$p.value)
statistic_list <- lapply(as.data.frame(t_test_list),function(x) x$statistic)
```

`p_value_list`

and `statistic_list`

are `p.value`

and `statistic`

for each 5 rows.