- nrow in R returns number of rows of a data frame or matrix
- ncol in R returns number of columns of a data frame or matrix
- dim in R returns or assigns the number of rows and column of a data frame or matrix.
- dimnames in R returns or assigns the row names and column names of a data frame
nrow in R:
nrow in R returns the number of rows of a data frame or matrix. Let’s use the mtcars data frame to demonstrate nrow function in R
# number of rows of a data frame - nrow function in R nrow(mtcars)
so the output will be
ncol in R:
ncol in R returns the number of columns of a data frame or matrix. Let’s use the mtcars data frame to demonstrate ncol function in R
# number of columns of a data frame. ncol(mtcars)
so the output will be
dim in R:
dim in R can be used to
- Get the number of rows and number of columns of a data frame
- Assign the number of rows and number of columns while creating the data frame.
Get the number of rows and columns in a data frame:
# number of rows and number of columns of a data frame in R. dim(mtcars)
output:
Assign the number of rows and columns to a matrix or data frame:
# Assign number of rows and number of columns of a matrix in R. x <- 1:12 dim(x) <- c(3,4) x
dim() function assigns the number of rows and number of columns of a matrix in above example.so the vector sequence from 1 to 12 is assigned in a 3 * 4 matrix
output:
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
dimnames in R
dimnames in R can be used to
- Get the row names and column names of a data frame or matrix
- Assign the names to rows and columns while creating the data frame or matrix.
Get the row names and column names of a data frame:
# row names and column names of a data frame in R. dimnames(mtcars)
the dimnames function in R returns the dimension names i.e row names and column names in the list format
output:
[1] “Mazda RX4” “Mazda RX4 Wag” “Datsun 710” “Hornet 4 Drive”
[5] “Hornet Sportabout” “Valiant” “Duster 360” “Merc 240D”
[9] “Merc 230” “Merc 280” “Merc 280C” “Merc 450SE”
[13] “Merc 450SL” “Merc 450SLC” “Cadillac Fleetwood” “Lincoln Continental”
[17] “Chrysler Imperial” “Fiat 128” “Honda Civic” “Toyota Corolla”
[21] “Toyota Corona” “Dodge Challenger” “AMC Javelin” “Camaro Z28”
[25] “Pontiac Firebird” “Fiat X1-9” “Porsche 914-2” “Lotus Europa”
[29] “Ford Pantera L” “Ferrari Dino” “Maserati Bora” “Volvo 142E”
[1] “mpg” “cyl” “disp” “hp” “drat” “wt” “qsec” “vs” “am” “gear” “carb”
Assign row names and column names to a matrix or data frame:
# Assign row names and column names to a matrix in R. x <- 1:12 dim(x) <- c(3,4) dimnames(x) <- list(c("x","y","z"),c("a","b","c","d")) x
dimnames() function assigns the row names and column names to a matrix in above example.
output:
a b c d
x 1 4 7 10
y 2 5 8 11
z 3 6 9 12