I have a dataframe:
df1
vec1 vec2 vec3 vec4 vec5
0 10 5 12 5
10 20 13 1 7
20 30 28 13 16
And I perform combn() on it:
x = combn( df1[,1:4] , 3 )
Which returns a matrix like this:
x
V1 V2
c(0,10,20) c(0,10,20)
c(10,20,30) c(5,13,28)
c(5,13,28) c(12,1,13)
And I want to obtain a vector where each element going down is the median value of each n in c(n,n+1,n+2) of each column of x. Like this:
y
V1 V2
5 #(median of 0,10,5) 5 #(median of 0,5,12)
13 #(median of 10,20,13) 10 #(median of 0,5,12)
28 #(median of 20,30,28) 20 #(median of 20,28,13)
So you see it is transformed so that each item going down the vectors in y is the median of each n element in the original combn() vectors of lists.
We can use apply()
to apply combn()
over the rows, then use the median()
function in combn()
, transposing the result.
t(apply(df1[1:4], 1, combn, 3, median))
# [,1] [,2] [,3] [,4]
# [1,] 5 10 5 10
# [2,] 13 10 10 13
# [3,] 28 20 20 28
Data:
df1 <- structure(list(vec1 = c(0L, 10L, 20L), vec2 = c(10L, 20L, 30L
), vec3 = c(5L, 13L, 28L), vec4 = c(12L, 1L, 13L), vec5 = c(5L,
7L, 16L)), .Names = c("vec1", "vec2", "vec3", "vec4", "vec5"), class = "data.frame", row.names = c(NA,
-3L))