Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do ncol and nrow only yield NULL when I do have data?

Tags:

r

I am new to R, so most likely this is a silly question.
Every time I create artificial data, and sometimes using imported data sets, R tells me my variables have no rows or columns.
I can run regressions but I cannot base commands on the number of rows/columns my variables have.
For instance, say I have a variable x1, which is a column vector of 100 observations.

ncol(x1)

NULL

nrow(x1)

NULL

However, if I do this:

x=t(x)
x=t(x)

and type again ncol(x), nrow(x), then I get the actual number of columns, rows that the object has.

Why is this happening and how can I fix this without having to use t()?

like image 947
Goose Avatar asked Dec 28 '14 08:12

Goose


People also ask

What is the difference between NROW and NROW in R?

Run it with atomic vectors, nrow will return NULL but NROW will give the length.

What is NROW in R?

nrow() function in R Language is used to return the number of rows of the specified matrix.


1 Answers

You need to use NCOL(x) and NROW(x) for a vector. By transposing x (t(x)) you turn it into a matrix, thus ncol(x) and nrow(x) work then.

It's in the help file:

?ncol nrow and ncol return the number of rows or columns present in x. NCOL and NROW do the same treating a vector as 1-column matrix.

> x <- 1:100
> is.matrix(x)
[1] FALSE
> NCOL(x)
[1] 1
> y <- t(x)
> is.matrix(y)
[1] TRUE
> ncol(y)
[1] 100
like image 141
erc Avatar answered Sep 22 '22 08:09

erc