Reputation: 1303
I have an array consisting many 2*3 matrices.
I want to give same row names to both rows of each matrix in my array. I'm trying dimnames()
, however I'm not getting what I want.
c1a <- c("1a","1a","1a")
c1b <- c("1b","1b","1b")
c2a <- c("2a","2a","2a")
c2b <- c("2b","2b","2b")
c3a <- c("3a","3a","3a")
c3b <- c("3b","3b","3b")
df1 <- as.data.frame(rbind(c1a,c2a,c3a))
df2 <- as.data.frame(rbind(c1b,c2b,c3b))
my.arr <- simplify2array(unname(Map(rbind, asplit(df1, 1), asplit(df2,
1))))
dimnames(Y)[[1]] <- c("a", "b")
Upvotes: 2
Views: 863
Reputation: 886938
We could just do this with dimnames
. There is no need for any looping
dimnames(my.arr)[[1]] <- c('a', 'b')
-output
> my.arr
, , 1
V1 V2 V3
a "1a" "1a" "1a"
b "1b" "1b" "1b"
, , 2
V1 V2 V3
a "2a" "2a" "2a"
b "2b" "2b" "2b"
, , 3
V1 V2 V3
a "3a" "3a" "3a"
b "3b" "3b" "3b"
Upvotes: 2
Reputation: 388797
Use apply
over 3rd dimension -
apply(my.arr, 3, function(x) {rownames(x) <- c('a', 'b');x}, simplify = FALSE)
#[[1]]
# V1 V2 V3
#a "1a" "1a" "1a"
#b "1b" "1b" "1b"
#[[2]]
# V1 V2 V3
#a "2a" "2a" "2a"
#b "2b" "2b" "2b"
#[[3]]
# V1 V2 V3
#a "3a" "3a" "3a"
#b "3b" "3b" "3b"
Upvotes: 2