4.5 C
London
Thursday, December 19, 2024
HomeRImport & Export Data in RHow to Use read.table in R (With Examples)

How to Use read.table in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the read.table function to read in a file that contains tabular data into R.

This function uses the following basic syntax:

df table(file='C:\Users\bob\Desktop\data.txt', header=FALSE, sep = "")

By default, the read.table function assumes there is no header row in the file and that the values are separated by white space.

However, you can use the header and sep arguments to tell R that the file has a header row and uses a different delimiter.

For example, you could choose to use a comma as a delimiter:

df table(file='C:\Users\bob\Desktop\data.txt', header=TRUE, sep=',')

The following step-by-step example shows how to use the read.table function in practice.

Step 1: View the File

Suppose I have a file called data.txt on my Desktop that I’d like to read into R as a data frame:

Step 2: Use read.table() to Read File into Data Frame

Next, let’s use read.table() to read the file into a data frame called df:

#read file from Desktop into data frame
df table(file='C:\Users\bob\Desktop\data.txt', header=TRUE)

Note that I specified header=TRUE since the first row in the file contains column names.

I also didn’t specify the sep argument since the data in the file is already separated by white space.

Step 3: View the Data Frame

Next, we can view the data frame to ensure that the file was read correctly:

#view data frame
print(df)

  var1 var2 var3
1    1    7    3
2    2    3    7
3    3    3    8
4    4    4    3
5    5    5    2
6    6    7    7
7    9    9    4

We can see that the data frame matches the data in the file.

We can also use the class and dim functions to check the class of the data frame and get the dimensions (number of rows and number of columns):

#check class of data frame
class(df)

[1] "data.frame"

#check dimensions of data frame
dim(df)

[1] 7 3

We can see that df is indeed a data frame and has 7 rows and 3 columns.

Additional Resources

The following tutorials explain how to read other types of files into R:

How to Import CSV Files into R
How to Import Excel Files into R
How to Import TSV Files into R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories