R/tidyverse: calculating standard deviation across rows

后端 未结 6 1076
情深已故
情深已故 2020-12-19 05:53

Say I have the following data:

colA <- c(\"SampA\", \"SampB\", \"SampC\")
colB <- c(21, 20, 30)
colC <- c(15, 14, 12)
colD <- c(10, 22, 18)
df &l         


        
6条回答
  •  醉梦人生
    2020-12-19 06:33

    Try this (using), withrowSds from the matrixStats package,

    library(dplyr)
    library(matrixStats)
    
    columns <- c('colB', 'colC', 'colD')
    
    df %>% 
      mutate(Mean= rowMeans(.[columns]), stdev=rowSds(as.matrix(.[columns])))
    

    Returns

       colA colB colC colD     Mean    stdev
    1 SampA   21   15   10 15.33333 5.507571
    2 SampB   20   14   22 18.66667 4.163332
    3 SampC   30   12   18 20.00000 9.165151
    

    Your data

    colA <- c("SampA", "SampB", "SampC")
    colB <- c(21, 20, 30)
    colC <- c(15, 14, 12)
    colD <- c(10, 22, 18)
    df <- data.frame(colA, colB, colC, colD)
    df
    

提交回复
热议问题