Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why nrow(dataframe) and length(dataframe) in r give different results?

Tags:

r

I have a ordered data frame and want to know the number of the last row.

data_ranking <- reduced_data[order(reduced_data$outcome,reduced_data$hospital,na.last=NA),]
nobs <- nrow(data_ranking)

gives me different results of

data_ranking <- reduced_data[order(reduced_data$outcome,reduced_data$hospital,na.last=NA),]
nobs <- length(data_ranking)

I would like to understand why is that. It seems that nrowgives me the answer I'm looking for, but I don't understand why.

like image 998
Laura Fernanda Avatar asked Feb 10 '16 02:02

Laura Fernanda


People also ask

What is length of data frame in R?

The length of a data frame is the number of columns present in the data frame.

What does NROW and NCOL mean in R?

The nrow() function returns the number of rows present in a given data frame, while the ncol() function returns the number of columns present in a data frame.

What is the difference between Cbind and data frame?

frame() function works very similarly to cbind() – the only difference is that in data. frame() you specify names to each of the columns as you define them. Again, unlike matrices, dataframes can contain both string vectors and numeric vectors within the same object.

What is the function in R to get the number of observations in a data frame?

The function str() shows you the structure of your data set. For a data frame it tells you: The total number of observations (e.g. 32 car types) The total number of variables (e.g. 11 car features) A full list of the variables names (e.g. mpg , cyl ... )


1 Answers

data frames are essentially lists where each element has the same length.

Each element of the list is a column, hence length gives you the length of the list, usually the number of columns.

nrow will give you the number of rows, ncol (or length) the number of columns.

The obvious equivalence of columns and list lengths gets messy once we have nonstandard structures within the data.frame (eg. matrices) and

 x <- data.frame(y=1:5, z = matrix(1:10,ncol=2))
 ncol(x) 
 # 3
 length(x) 
 # 3


 x1 <- data.frame(y=1:5, z = I(matrix(1:10,ncol=2)))

 ncol(x1) 
 # 2
 length(x) 
 # 2
like image 100
mnel Avatar answered Oct 04 '22 00:10

mnel