Reading and writing Rectangular Text Data Using readr Package
Suppose we have datset containing student information about their name, class and marks etc. So, we want information of category = ‘ female’. The output file will contain the information of female student only. The readr package is primarily used for reading structured text data into R. It provides functions to efficiently read various types of delimited files like CSV, TSV, and fixed-width format files. Here are some additional examples and explanations of how to use the readr package in R. Use dataset StudentsPerformance
Step 1: The “readr” package from CRAN (Comprehensive R Archive Network) get installed with install.packages(“readr”). The R environment is loaded with the “readr” package within library(readr).
Step 2: The read_csv() function only reads the CSV file into a dataframe: read_csv(), a function from the “readr” package, reads a CSV file and creates a dataframe. sales_data – read_csv(“StudentsPerformance.csv”) reads the CSV file “StudentsPerformance.csv” and load the data in a dataframe named sales_data.
Step 3: modified_data <- sales_data’female’ is the value for sales_data$gender. Adjusting the sales_data dataframe to only contain rows where the “gender” column is “female” results in the creation of a new dataframe called modified_data. To filter rows based on the “gender” column, indexing and a logical condition are used.
Step 4: Write_csv(modified_data, “femalecategory.csv”) generates a new CSV file called “femalecategory.csv” from the modified_data dataframe. The “readr” package’s write_csv() function writes a dataframe to a CSV file.
R
install.packages ( "readr" ) library (readr) sales_data <- read_csv ( "StudentsPerformance.csv" ) print (sales_data) # Make some modifications to the data modified_data <- sales_data[sales_data$gender == 'female' ,] # Write the modified data to a new CSV file write_csv (modified_data, "femalecategory.csv" ) |
Output:
Read and Write Rectangular Text Data Quickly using R
Reading and writing rectangular text data quickly in R Programming Language can be achieved using various packages and functions, depending on your specific needs and the data format. Two commonly used packages for this purpose are readr and data. table. Here’s how you can do it with these packages.