HOW TO IMPORT DATA IN R
R can import data from a variety of sources. It can import
data from excel files , comma separated files , tab separated files , special
character delimited files, a SQL Server , Oracle Server or any database system
that supports ODBC driver.
In this article, I will be demonstrating how to do this from
a couple of sources.
Let’s start with the simplest of them all.
Comma Separated Files:
Comma separated files are files where columns in your data
are separated by commas. A typical comma separated file would look like this.
Now, we will see how we can import it in R.
R has a built in function to import comma separated files in
R. We will use it to import file.
read.csv(file = "E:\Data Analytics\a.txt" ,
header = TRUE , sep = ",")
Now, I will explain this command in detail.
·
Read.csv is the function used to import file in
R.
·
File parameter is used to provide R the file
path where file is located.
·
Header is a Boolean parameter used to indicate
whether first row of the file is header or data. TRUE indicates that first line
is header.
·
Sep tells R what is the separator used to
separate the columns in the file.
Well, so far so good. So now we can see our file’s data in
R. But just seeing it is not good enough. We need to store it in R so that it
can be processed further.
The command to do that is simple. All you need to do is to
add a variable where we need to store this file’s data rather than displaying
it.
a = read.csv(file = "E:\Data
Analytics\a.txt" , header = TRUE , sep = ",")
That’s it. This command will store the contents of the file
in an R variable called a. We can see the variable a in R studio’s environment
as well. We can see that it also has same number of rows and columns as the
file.
If we want to see what this variable holds, we can just see
it as shown below.
a
So now we can see the same data from file in a new R
variable called a. So now we have imported a comma separated file in R.
| Separated Files:
But sometimes we may get a different file separator than
comma. Let’s assume that we got | as separator.
Well, we use the same command, but just change the sep
parameter in the command to our new separator.
a = read.csv(file = "E:\Data Analytics\a.txt"
, header = TRUE , sep = "|")
As you can see, I have changed the separator to | in sep
parameter.
Once we run this, once again all the data from a file
separated by | will be stored in variable named a.
So as you can see importing data in R is as easy as it gets.
Comments
Post a Comment