R: Get column size using index

Viewed 88

I'd like to get the size of a column using the index. I tried using the length() function with the column index inside, but it doesn't work:

length(bd[7])

I'm sorry if this is too basic, I'm new to R. Thank you!

1 Answers

The bd[7] is still a data.frame with single column and length for a data.frame is by default the number of columns. We need to extract the column as a vector and then use length. Extraction of column depends on the class i.e. if it is a data.frame/matrix, then bd[,7] would drop the dimensions and return a vector, but it is not the case with data.table/tibble. However, all of them works with either $ or [[

length(bd[[7]])

Or if it is a data.frame or vector, NROW would still work though

NROW(bd[7])

i.e.

> NROW(1:7)
[1] 7
> NROW(data.frame(col1 = 1:7))
[1] 7
Related