Goose
Goose

Reputation: 193

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

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()?

Upvotes: 18

Views: 27493

Answers (1)

erc
erc

Reputation: 10133

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

Upvotes: 33

Related Questions