Reputation: 461
I am using this code to make a matrix:
input1 <- read_excel("input.xlsx")
MAT <- as.matrix(input1[,2:400])
Height <- MAT[1,]
Expres <- MAT[2:36000,]
row.names(Expres) <- input1[2:36000, 1]
My input data has 400 samples
with 36000 genes
and Height
in row 2 and the data subset looks like:
Gene Sample1 Sample2 -- Sample400
Height 5 10 -- 7
Gene1 0.5 0.6 -- 0.9
Gene2 0.4 0.7 -- 0.3
Gene36000 0.5 0.6 -- 0.1
but I am getting an error for the last line:
Error in dimnames(x) <- dn :
length of 'dimnames' [1] not equal to array extent
I will appreciate any help. Thank you!
Upvotes: 0
Views: 665
Reputation: 160792
Assuming you are using readxl::read_excel
, it's returning a tibble
, and [
indexing is not doing what you expect.
Your expectation works with a data.frame
:
mtcars[2:3,1]
# [1] 21.0 22.8
but not with a tibble
:
as_tibble(mtcars)[2:3,1]
# # A tibble: 2 x 1
# mpg
# <dbl>
# 1 21
# 2 22.8
as_tibble(mtcars)[[1]][2:3]
# [1] 21.0 22.8
Instead, use
row.names(Expres) <- input1[[1]][2:36000]
Incidentally, the expected behavior can be forced in both directions
mtcars[2:3, 1, drop = FALSE]
# mpg
# Mazda RX4 Wag 21.0
# Datsun 710 22.8
as_tibble(mtcars)[2:3, 1, drop = TRUE]
# [1] 21.0 22.8
Sadly, the use of drop=
works with data.frame
and tbl_df
, but not with the third data.frame
variant data.table
:
library(data.table)
as.data.table(mtcars)[2:3, 1, drop = TRUE]
# mpg
# 1: 21.0
# 2: 22.8
as.data.table(mtcars)[2:3, 1, drop = FALSE]
# mpg
# 1: 21.0
# 2: 22.8
as.data.table(mtcars)[[1]][2:3]
# [1] 21.0 22.8
(A source of many hours of trouble-shooting for me some time ago.)
Upvotes: 2