Skip to content

Topic: R

  • Tip: Reading CSV data with R

    To read data with R, use the following procedure:
    1. Make sure you are in the correct directory. Use the getwd() function to get the current working directory.

    Screenshot of getwd() function

    2. Make sure that the file you wish to load is in the selected directory. Otherwise use the setwd() function to set the correct directory.

    Screenshot of setwd function.

    3. Use the list.files() function to list the files in the directory and check that the file is in the correct location.

    Screenshot of output of list.files function

    4. Read the CSV file into a variable (e.g. mydata) using the read.csv() function.

    Result of reading data using read.csv() function in R

    5. To view the data, use the View() function.

    View the data using the View() function

    Potential Errors

    One of the potential errors that you can get is the following:

    R
    data <- read.csv("adult.test", header=TRUE, sep=",")
    R
    Error in read.table(file = file, header = header, sep = sep, quote = quote,  : 
      duplicate 'row.names' are not allowed

    This error can be solved by the row.names=NULL parameter, as shown in the following code:

    R
    data <- read.csv("adult.test", header=TRUE, sep=",", row.names=NULL)