Read Data from CSV File

Introduction to Read Data From CSV File

In R Language one can easily read data from CSV file format. One can use the read.csv() function. There are different ways to read the CSV file in R and the read.csv() function has many useful arguments.

It is important to note that a CSV file is a comma-separated value file. Usually, CSV files are generated from spreadsheet-like software such as MS Excel. Regarding the file type CSV files are very similar to txt files, however, CSV files can be easily opened in MS Excel. The read.csv() function imports the CSV file as a data frame in R Language, a fundamental data structure in R.

read.csv Function in R

Using the read.csv function in R one can read the data from a CSV file by choosing the file (a dialog box opens to select the appropriate file). This is the easy way to choose a data file as the user does not need to type the file path. For example,

data <- read.csv(file.choose(),header =TRUE)

The file.choose() argument will open a dialog box for the selection of the required file.

Read Data from CSV File

After selecting the data file, one can use the data and may display and get the data information, such as

head(data)
str(data)

There is another way to read the data by giving the complete path to the file with the data file name and its extension. The read.csv function in R can be used with important arguments, such as file path and header=TRUE.

data <- read.csv("C:\\book1.csv", header=TRUE)
data <- read.csv("C:\\mywork\\data\\book1.csv", header=TRUE)

After reading the data file, one can check the names of each variable by using names() function.

names(data)

Selecting Variables from Data Object

One can select a column (variable) by using square brackets and column index or by use of a dollar sign. For example

data$X1    # Selects the variable X1
data[, 1]  # selects the variable in column 1
data[, 4]  # selects the variable in column 4
data[, 1:3] # selects column 1, 2 and 3 

Similarly, one can also select the rows from a data file. For example

data[12, ]   # select the 12 observation/ row of all variables (columns)
data[5:10, ] # selects rows 5 to 10 with all columns/variables

One can also subset the data by using some conditional operator. For example, the following command reads $X_1$ variable from data having greater than 0.7 values.

data1[data1$X1 > 0.7, ]

Read a CSV File as a Table

One can also read a CSV file as a table. For example,

data <- read.table("C:\\data.csv",sep ",",header True)

Some important arguments related to read.csv() function:

  • file: The file argument is used to specify the path to the CSV file. One can provide either the absolute path (e.g., “C:/Users/yourname/Documents/data.csv”) or the relative path if the file is in the working directory.
  • header (optional): The header argument is logical (either TRUE or FALSE), it indicates whether the first row of the CSV file contains names of the columns. By default, header=TRUE. In case, if the file does not have a header row, set it header=FALSE.
  • sep (optional): The sep argument specifies the delimiter (separator) used between values in the CSV file. The default is a comma (“,”).
  • dec (optional): The dec argument defines the decimal point character used in the CSV file. The default is “.”.
RFAQS.com Read Data From CSV File

https://itfeature.com

https://gmstat.com

Import Data Files Into R Language

You can read/import data files into R that are produced by different software such as MS Excel, Minitab, SPSS, SAS, and STATA.

Import Data Files into R Language

In R language different data file formats can be read or imported easily. Let us start learning about how to import Data Files into R Language such as Excel, SPSS, STATA, SAS, Minitab, etc format.

Reading Excel Files in R

The XLConnect package can be used to import data files into R produced in MS Excel. First, you have to install this package.

install.packages("XLConnect")

You can check if the package is already installed using the code:

any(grepl("XLConnect", installed.packages()))

If the package is installed, you need to activate the package in your workspace (using library( ) function) to load data from MS Excel files.

importing Data Files into R Language

Suppose, you have a data file (Hald.xlsx) stored at the path "D:\STAT\STA-654\Hald.xlsx". To read this file the readWorksheetFromFile( ) function can be used. For example,

library(XLConnect) 
data &lt;- readWorksheetFromFile("D:/stat/sta-654/Hald.xlsx", sheet=1)

Since an Excel workbook can contain more than one sheet, therefore, you need to specify the sheet argument and specify which sheet you want to load into R. In this example, data from sheet 1 will be loaded.

If you want to load the whole workbook (all sheets) use the loadWorkbook( ) function to load the required worksheet as a data file frame. For example,

wb <- loadWorkbook("D:/stat/sta-654/Hald.xlsx") 
df <- readWorksheet(wb, sheet = 1)

The readxl package can also be used to read MS Excel files more easily.

library(readxl) 
df <- read_excel("Data file with path")

Note that the MS Excel files with extension: *.xls, or *.xlsx can be specified. The sheet argument can also be added, just like with the XLSconnect package.

Read SPSS Data Files

To read the SPSS files install foreign package. After loading the foreign package, the read.spss( ) function can be used to load an SPSS data file in R. For example,

library(foreign) 
mydata &lt;- read.spss ("SPSS data file with path", to.data.frame = TRUE)

The argument to.data.frame is set to TRUE so that the data is displayed in a data frame format. Since the SPSS data file contains value labels, and if you do not want the variables with value labels to be converted into R factors with corresponding levels, setuse.value.labels = FALSE. For example,

library(foreign) 

mydata <- read.spss("SPSS data file with path", 
                    to.data.frame = TRUE, 
                    use.value.labels = FALSE)

Reading STATA Data Files

To import Stata files the read.dta( ) function from the foreign package can be used. For example,

library(foreign) 
mydata &lt;- read.dta("STATA file with path")

Reading SAS Data Files

The read.sas7bdat( ) function from sas7bdat package can be used to read SAS data files into R.

library(sas7bdat) 
mydata &lt;- read.sas7bdat("SAS data file with path")

Reading Minitab Data File

Minitab data files can be imported in R using read.mtp( ) function from foreign package.

library(foreign) 
mydata &lt;- read.mtp("Minitab data file with path")

Reading RDA or RData Files

The R data files RDA and RData files can be easily read using load( ) function.

load("filename.RDA")

https://itfeature.com

https://gmstat.com

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