rfor-loopmedian

Finding the median of every 3 rows in a data set


I'm currently analysing reaction time data on R. For every block a button is pressed thrice. I have every block together in a data frame in R strecthing from Block 1 - Block 10. I would like to sample the column median of each block, and then use it to construct a graph detailing change in median reaction time over the blocks.

I will admit I am a coding novice and have struggled a lot with this. Any help greatly appreciated.


Solution

  • As mentioned, some more details about how your data actually look would help a lot. But I'll take a stab at it regardless. I'm guessing you are saying you have all the values in a single column in a data frame, and need to group them by 3, and find the median of those 3 values, for each of 10 blocks. As long as the values are ordered by group the solution below should work. It just converts the data into a matrix, then applies the median function to each column of that matrix. Output is a list of 10 medians, you could plot these or do whatever else you need.

    #simulate the data, you don't need this part
    Values = rnorm(30,0,1) #30 random values (3 for each of 10 blocks), from simple normal dist
    
    
    #Actual Solution
    ValuesAsMatrix=matrix(Values,nrow=3)
    Medians = apply(ValuesAsMatrix,2,median) # 2 indicates apply to columns, 2nd dimension
    
    

    Even if this isn't the exact structure of your problem, the general solution of getting these values into either the rows/columns of a matrix by group, then applying a solution should work. Let me know if this works for you, if not try to provide more context in any follow up questions on this.