Learner
Learner

Reputation: 757

how to find median across each column for certain row

I have a data which looks like this

df<- structure(list(time = structure(1:12, .Label = c("M11", "M12", 
"M13", "M14", "M15", "M16", "M51", "M52", "M53", "M54", "M55", 
"M56"), class = "factor"), grp = structure(c(1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "TT", class = "factor"), 
    X2 = c(36034L, 63763L, 51432L, 65100L, 61444L, 71012L, 266610L, 
    389787L, 47659L, 63156L, 84593L, 84331L), X3 = c(45632L, 
    66505L, 60360L, 36685L, 107551L, 53360L, 323952L, 344944L, 
    69601L, 51268L, 130665L, 59704L), X4 = c(59025L, 52837L, 
    68571L, 35788L, 75262L, 66601L, 424683L, 340948L, 79487L, 
    42809L, 95607L, 81739L), X5 = c(74767L, 48210L, 70972L, 67705L, 
    85576L, 89265L, 393380L, 306633L, 77816L, 73611L, 106317L, 
    116890L), X6 = c(50846L, 37970L, 63896L, 78296L, 81216L, 
    62308L, 62613L, 21770L, 80955L, 88832L, 97586L, 68345L), 
    X7 = c(26688L, 27830L, 17010L, 54074L, 26727L, 31109L, 24448L, 
    38701L, 17378L, 46327L, 25324L, 25325L)), class = "data.frame", row.names = c(NA, 
-12L))

I am trying to get the median for each column for two of we have M1 and M5. I want to have the median for each column of M11, M12, M13, M14, M15, M16 and then for M51, M52, M53, M54, M55, M56

I tried to work with apply but I cannot figure it out

apply(df[,-c(1,2)], 1, function(x) tapply(x, df[,1], median))

I want the format like this

time grp       2       3       4       5       6        7
M1  TT1-6   62603.5 56860   62813   72869.5     63102   27278.5
M5  TT1-6   84462   100133  88673   111603.5    74650   25324.5

Upvotes: 2

Views: 57

Answers (1)

akrun
akrun

Reputation: 886938

We can use tidyverse. Extract the substring of the 'time', use it in the group_by along with 'grp' column and then use summarise_all to the 'median' and 'sd' of all the columns

library(dplyr)
df %>%
   group_by(time = substr(time, 1, 2), grp) %>% 
   summarise_all(funs(median, sd))

Upvotes: 2

Related Questions