Reputation: 17
I need to calculate means for each row in data for each group of columns, so I want to use a loop for it, cause my date dimension is around 500 000x1000. My data looks similar like this:
var a1 var a2 var b1 var b2 var c1 var c2 var d1 var d2 var e1 var e2
[1,] 7 9 9 8 3 5 1 1 7 8
[2,] 3 9 9 9 6 6 8 1 9 5
[3,] 7 8 10 8 7 5 2 3 9 7
[4,] 5 10 7 4 6 1 6 1 9 3
I can calculate means this way and it works well but i have around 200 groups
rowMeans(x[,1:2])
How can I make a loop for rowMeans to calculate means for each group of columns like'var a', 'var b", etc. I am new in R, so any help is greatly appreciated.
Upvotes: 0
Views: 71
Reputation: 12559
Here is a solution using a 3-dimensional array:
x <- read.table(text=
" 7 9 9 8 3 5 1 1 7 8
3 9 9 9 6 6 8 1 9 5
7 8 10 8 7 5 2 3 9 7
5 10 7 4 6 1 6 1 9 3")
x <- as.matrix(x)
apply(array(x, dim=c(4, 2, ncol(x)/2)), c(1,3), mean)
# > apply(array(x, dim=c(4, 2, ncol(x)/2)), c(1,3), mean)
# [,1] [,2] [,3] [,4] [,5]
# [1,] 8.0 8.5 4.0 1.0 7.5
# [2,] 6.0 9.0 6.0 4.5 7.0
# [3,] 7.5 9.0 6.0 2.5 8.0
# [4,] 7.5 5.5 3.5 3.5 6.0
For generating nice column names you can do (solution similar to that from @Ronak):
x <- as.matrix(x)
colnames(x) <- c("vara1", "vara2", "varb1", "varb2", "varc1", "varc2", "vard1", "vard2", "vare1", "vare2") # original colnames
y <- apply(array(x, dim=c(4, 2, ncol(x)/2)), c(1,3), mean)
cn <- colnames(x)[c(TRUE, FALSE)]
colnames(y) <- sub("var(.*)\\d+", "\\1", cn)
y
Upvotes: 1
Reputation: 388862
We can use split.default
to split the columns based on common column names and then take rowMeans
of each list.
sapply(split.default(data.frame(x), sub("var(.)\\d+", "\\1",colnames(x))), rowMeans)
# a b c d e
#[1,] 8.0 8.5 4.0 1.0 7.5
#[2,] 6.0 9.0 6.0 4.5 7.0
#[3,] 7.5 9.0 6.0 2.5 8.0
#[4,] 7.5 5.5 3.5 3.5 6.0
where
sub("var(.)\\d+", "\\1",colnames(x)) #returns
#[1] "a" "a" "b" "b" "c" "c" "d" "d" "e" "e"
data
Assuming x
is a matrix.
x <- structure(c(7L, 3L, 7L, 5L, 9L, 9L, 8L, 10L, 9L, 9L, 10L, 7L,
8L, 9L, 8L, 4L, 3L, 6L, 7L, 6L, 5L, 6L, 5L, 1L, 1L, 8L, 2L, 6L,
1L, 1L, 3L, 1L, 7L, 9L, 9L, 9L, 8L, 5L, 7L, 3L), .Dim = c(4L,
10L), .Dimnames = list(NULL, c("vara1", "vara2", "varb1", "varb2",
"varc1", "varc2", "vard1", "vard2", "vare1", "vare2")))
Upvotes: 2