Reading Text Files In R Language: A Quick Guide

We can import data that is already saved (available) in a file created in text (*.txt) files, MS Excel, SPSS, or some other software. Before importing/reading data stored in a file (that is, reading text files in R), one should be clear and understand the following:

  1. Usually, data from spreadsheets reserved the first row as header (name of variables), while the first column was used to identify the sampling unit (observation number).
  2. Avoid names, and the value of fields with blank spaces, each word may be interpreted as a separate variable, resulting in errors.
  3. To concatenate words, use a full stop (.) instead of space between words.
  4. Name variables with short or abbreviated names.
  5. Try to avoid using names of variables that contain symbols such as ?, $, %, ^, *, (, ), -, #, <, >, /, |, ,\, [, ], {, and }.
  6. Delete comments you have made in your Excel file.
  7. Make sure missing values in your dataset are indicated with NA.

Preparing R workspace

Before importing data in R, it is better to delete all objects using the following line of code

rm(list = ls() )

The rm( ) function “remove objects from a specified environment”. Since no argument to ls( ) function is provided, datasets and user-defined functions will be deleted.

Confirm your working directory before importing a file to R, using

getwd()

If possible change the path of your working directory. such as

setwd("D:\\Stat\\STA-654")

Note you may have to create the directory (folder) and the path discussed above.

Reading Text Files in R

Reading Text Files In R Language

Reading Text files in R is easy and simple enough. If you have data in a *.txt file or a tab-delimited text file, you can easily import it with the read.table( ) function. Suppose we have a data file named "Hald.txt" stored at the path "D:\STAT\STA-654\Hald.txt". The following code line can be used for reading text files in R:

datafile <- read.table ("D:/stat/sta-654/Hald.txt", header = TRUE)

If you have data stored on some web address, you can also import it as

datafile <- read.table ("http://itfeature.com/wp-content/uploads/2020/03/Hald.txt", header = TRUE)

Note that the first argument of read.table() provide the name and extension of the file that you want to import in R. The header argument specifies whether or not you have specified column names in your data file. The Hald.txt file will be imported as data.frame an object.

Computer MCQs Online Test

MCQs in Statistics

Load Data from R Library (2020)

Here we will discuss how to read the data from R library. Many R libraries contain datasets, which may be called data libraries. For example, the car package contains a Duncan dataset that can be used for learning and implementing different R functions. To use Duncan’s data, first, you have to load the car package. Note that the car package must be installed to make use of the Duncan dataset. Let us read data from the R library and make use of the Duncan dataset.

Getting Data from R Library

To Read or load Data stored in an R library, one needs to load the library first.

library(car)
data(Duncan)
attach(Duncan)

If the car the package is not installed on your system, one can install using the following command. Note your system should be connected to the internet.

install.packages("car")

Reading Data from R Library

The attach( ) function makes each variable accessible without writing the variable name with the respective dataset name. After attaching the Duncan dataset one can access the variable say education instead of writing Duncan$education. Let us make some functions to read data from R library.

head(Duncan)

The head( ) function will display the top six observations with their variable names in table-type format. It will help to understand the structure of the dataset.

summary(Duncan)

For quantitative variables, the summary( ) function will provide five-number summary statistics with the mean value. For qualitative variables, the summary( ) function will provide the frequency of each group.

To plot a scatter plot one can use the plot function. For example,

plot(education, income)
Scatter plot of Education and Income

The scatter plot shows the strength and direction of the relationship between “Percentage of occupational incumbents in 1950 who were high school graduates’ and ‘Percentage of occupational incumbents in the 1950 US Census who earned $3,500’.

Getting Basic Data Information

To check how many observations and columns are in a dataset, one can make use of nrow( ) and ncol( ) function. For example,

nrow(Duncan)
ncol(Duncan)

To get the definition of a dataset and its variable, one can read the dataset documentation:

?Duncan

To see the list of pre-loaded data, type the function data( ):

Reading Data from R Library
data( )

It is best practice to attach data only one at a time when reading data from the R library or importing from the data file. To remove a data frame from the search path, use detach()function.

Exercise for Data from R Library

Try the following dataset and make use of all the functions discussed in this lecture.

mtcars
iris
TootGrowth
PlantGrowth
USAarrests

SPSS Data Analysis

MCQs General Knowledge

JSON Files in R: Reading and Writing (2019)

Introduction to JSON Files in R

A JSON file stores simple data structures and objects in JavaScript Object Notation (JSON) format. JSON is a standard data lightweight interchange format primarily used for transmitting data between a web application and a server. The JSON file is a text file that is language-independent, self-describing, and easy to understand. In this article, we will discuss reading and writing a JSON file in R Language in detail using the R package “rjson“.

Since JSON file format is text only, it can be sent to and from a server and used as a data format by any programming language. The data in the JSON file is nested and hierarchical. Let us start reading and writing JSON files in R.

Creating JSON File

Let’s create a JSON file. Copy the following lines into a text editor such as Notepad. Save the file with a .json extension and choose the file type as all files(*.*). Let the file name be “data.json”, stored on the “D:” drive.

{ 
"ID":["1","2","3","4","5","6","7","8" ],
"Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ],
"Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ],
"StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013",
"7/30/2013","6/17/2014"],
"Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"]
}
Reading and Writing JSON files in R

Installing rjson R Package

The R language can also read the JSON files using the rjson package. To read a JSON data file, First, install the rjson package. Issue the following command in the R console, to install the rjson package.

install.packages("rjson")

The rjson package needs to be loaded after installation of the package.

Reading JSON Files in R

To read a JSON file, the rjson package needs to be loaded. Use the fromJSON( ) function to read the file.

# Give the data file name to the function.
result <- fromJSON(file = "D:\\data.json")
# Print the result.
print(result)

The JSON file now can be converted to a Data Frame for further analysis using the as.data.frame() function.

# Convert JSON file to a data frame.
json_data_frame <- as.data.frame(result)
print(json_data_frame)

Writing JSON objects to .Json file

To write JSON Object to file, the toJSON() function from the rjson library can be used to prepare a JSON object and then use the write() function for writing the JSON object to a local file.

Let’s create a list of objects as follows

list1 <- vector(mode="list", length=2)
list1[[1]] <- c("apple", "banana", "rose")
list1[[2]] <- c("fruit", "fruit", "flower")

read the above list to JSON

jsonData <- toJSON(list1)

write JSON object to a file

write(jsonData, "output.json")

Read more about importing and exporting data in R: see the post

MCQs General Knowledge