R ncol()

KyraThompson's avatar
Published Oct 7, 2022
Contribute to Docs

The ncol() function returns the number of columns in a data frame.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to code and clean and manipulate data for analysis and visualization with the R programming language.
    • Beginner Friendly.
      14 hours

Syntax

ncol(df_object)

The df_object parameter is the data frame passed into the ncol() function.

Example

The following example uses a CSV file named patients.csv with the following information:

First Name Last Name DOB
Kiercen Tremboly 06/24/1992
Phaedra Blackborn 08/19/1972
Toby Spencer 11/16/1953
Sandra Speller 07/05/1989

The data within the file can be read in and the ncol() function can be used to retrieve the number of columns:

# Read file
df <- read.csv("patients.csv")
# Retrieve number of columns
ncol(df)

This results in the following output:

3

All contributors

Contribute to Docs

Learn R on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to code and clean and manipulate data for analysis and visualization with the R programming language.
    • Beginner Friendly.
      14 hours