R:如何获取每n行的最小值和最大值或其他函数 [英] R: How to take the min and max or other functions of every n rows
问题描述
我有一个数据框,我将一个变量放入向量中.
I have a dataframe of which I put one variable into a vector.
从这个向量中,我想为每5个值计算mean
,min
和max
值.
From this vector, I would like to calculate for every 5 values mean
, min
and max
value.
我设法通过这种方式计算出平均值:
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 every five values?
另外,如何从每个n行的1样本t检验中获得统计量和p值?
Aditionally, how can I get statistic and p-value from a 1-sample t-test for each n-row?
推荐答案
您可以为此使用sapply
和split
:
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)))
更新
如何从每个n行的样本t检验中获取统计量和p值: 这将很难实施.看下面;
Update
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)
每5行
p_value_list
和statistic_list
分别是p.value
和statistic
.
p_value_list
and statistic_list
are p.value
and statistic
for each 5 rows.
这篇关于R:如何获取每n行的最小值和最大值或其他函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!