I have a data frame of 20 variables, each variable has 2 observations. I have computed all the possible pairs of variables with combn
, and now for each observation and each pair, I would like to compute the mean. 190 combinations are possible taking 2 elements of a data set of 2 variables.
So I have, for a data frame called A
with 20 variables (A1
-A20
) of 2 observations:
structure(list(A1 = c(-0.213231661750682, -0.221771671227651), A2 = c(-0.453268784292906, -0.411536539651889), A3 = c(-0.313590782870182, -0.32050845041221), A4 = c(-0.24068090024987, -0.237324659112412), A5 = c(-0.250518309189155, -0.243752386033467), A6 = c(-0.346513318287749, -0.310682137162937), A7 = c(-0.367893853843964, -0.389767604998544), A8 = c(-0.456036421130999, -0.476044422073483), A9 = c(-0.5235080360833, -0.424936488273877), A10 = c(-0.27421438645257, -0.254264546496442), A11 = c(-0.340599280820809, -0.378029798423225), A12 = c(-0.484056720613284, -0.497316258925064), A13 = c(-0.288377079820288, -0.279396742334153), A14 = c(-0.245523401712755, -0.248923757652515), A15 = c(-0.29225618208897, -0.253033910862832), A16 = c(-0.434525774496723, -0.515485159478136), A17 = c(-0.441791229146799, -0.44754900324085), A18 = c(-0.437452755366462, -0.405902999298872), A19 = c(-0.322178004640579, -0.321200331464843), A20 = c(-0.369930416907759, -0.376326662497664)), .Names = c("A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10", "A11", "A12", "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20"), row.names = 1:2, class = "data.frame")
B <- combn(A, 2, simplify=FALSE)
And for example the first element of B will be:
B[1]
A1 A2
-0.21 -0.45
-0.22 -0.41
and I need a list that returns 190 vectors with the mean of each observation between each pair of variable, like here for example a vector C
:
C
-0.33
-0.315
I have tried to use apply
, lapply
and sapply
but I'm still getting an error message (like dim(X) must have a positive length
). R stores each element of B
as a list of length=1
and can't compute the mean as such. I have tried to convert each element as a matrix but it put the two vector (A1
and A2
for ex) in a matrix[1,1]
.
How can I compute that, preferably using a function apply
since I have a lot of data?
We can loop through the list
'B" can get the mean
sapply(B, rowMeans)
Or as @d.b. mentioned , use the FUN
argument in combn
combn(A, 2, FUN = rowMeans)
set.seed(24)
A <- as.data.frame(matrix(sample(1:5, 5*20, replace = TRUE),
nrow = 5, ncol = 20, dimnames = list(NULL, paste0("A", 1:20))))