简体   繁体   English

一行上的R-最小值和最大值,定义为许多列

[英]R- min and max on a row, defined to a number of columns

I have 4 variables, each in triplicates, and I need to find the average for each triplicate, in each row, and on top of that find minimum and maximum for each 5th row, in order to plot error bars. 我有4个变量,每个变量一式三份,并且我需要在每一行中查找每个一式三份的平均值,并在其顶部找到每第5行的最小值和最大值,以便绘制误差线。 Here is an example with two variables: 这是带有两个变量的示例:

  x  a1  a2  a3  b1  b2  b3
220   2   7  71  28  53  31
221   5  13  85  33  51  34

So I need the average of a1-a3 when x=220, and so on, and then I need minimum and maximum for row 1, row 6 and so on. 因此,当x = 220时,我需要a1-a3的平均值,依此类推,然后我需要第1行,第6行的最小值和最大值,依此类推。 I assume I need to do this in order to get the data I need to make error bars, but I am new to R, so there might be a better way. 我想我需要这样做才能获取需要制作误差条的数据,但是我对R并不陌生,所以可能会有更好的方法。

May be this helps 也许这会有所帮助

library(dplyr)
library(tidyr)
add_rownames(df1) %>% 
        gather(Var, Val, -x, -rowname) %>% 
        extract(Var, into='Var', '([^0-9]*).*') %>%
        group_by(rowname, x, Var) %>% 
        summarise(Mean=mean(Val), Min=min(Val), Max=max(Val))

Or using base R 或使用base R

 res <-  do.call(rbind, 
             lapply(split(names(df1)[-1],
                sub('\\d+$', '', names(df1)[-1])), function(x) {
              x1 <- df1[x]
              data.frame(x=df1[1],Mean=rowMeans(x1), Max=do.call(pmax, x1),
                 Min=do.call(pmin, x1))}))

data 数据

df1 <- structure(list(x = 220:221, a1 = c(2L, 5L), a2 = c(7L, 13L), 
a3 = c(71L, 85L), b1 = c(28L, 33L), b2 = c(53L, 51L), b3 = c(31L, 
34L)), .Names = c("x", "a1", "a2", "a3", "b1", "b2", "b3"
 ), class = "data.frame", row.names = c(NA, -2L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM