How to Use read.delim in R?
In this article, we will learn how to use the read.delim() in the R Programming Language.
Example 1: Using read.delim() function to read a space-separated text file
The read.delim() function is used to read delimited text files in the R Language. It doesn’t need any external package to work. This function converts a delimited text file into a data frame and can be used to read a variety of space-separated files for example CSV.
Syntax:
read.delim( file, header)
where:
- file: determines the file name to be read with full path.
- header: A Boolean that determines whether the first line represents the header of the table. Default is TRUE.
Under this example, we are reading a data frame from a space-separated text file using the read.delim() function in R language.
Text file in use:
Program:
R
# read the space separated dataframe data_frame <- read.delim ( 'sample.txt' ) # view data frame data_frame |
Output:
group y x 1 category1 55 -0.15703480 2 category1 63 0.63781188 3 category1 62 -1.59689179 4 category1 59 -0.61527367 5 category1 64 0.80799947 6 category1 73 1.03513951 7 category1 56 0.67577537 8 category1 66 -0.37485984 9 category1 73 0.14448351 10 category1 68 -0.53013492 11 category1 63 0.57979608 12 category1 74 -0.08396805 13 category1 67 -0.63099142 14 category1 50 -0.49751923
Example 2: Using read.delim() function to read manual symbol separated text file
To read a text file separated by a manual symbol, we use the sep parameter to determine the symbol that separates the data in the text file. In this way, we can read comma-separated-values, tab-separated values, etc.
Syntax:
read.delim( file, sep)
where:
- file: determines the file name to be read with full path.
- sep: determines table delimiter. Default is a tab (\t).
In this example, we are reading a data frame from a comma-separated text file using the read.delim() function with the sep parameter in the R language.
Text file in use:
Program:
R
# read the tab separated dataframe data_frame <- read.delim ( 'my_data.txt' , sep= ',' ) # view data frame data_frame |
Output:
group y x 1 category1 63 0.95195245 2 category1 77 -1.68432491 3 category1 72 0.03062164 4 category1 67 -1.56885679 5 category1 69 -0.35835908 6 category1 53 -0.87003090 7 category1 73 -0.88877644 8 category1 64 0.67040206 9 category1 66 -0.20397715 10 category1 58 -0.29472917 11 category1 68 -1.47210730 12 category1 68 -1.40288930 13 category1 65 -0.14653898 14 category1 70 0.76216057 15 category1 71 -0.21718205 16 category1 64 0.72430687 17 category1 70 -0.24907560 18 category1 60 -1.24296149
Contact Us