Reading a CSV file
R has a rich set of functions. R provides read.csv() function, which allows us to read a CSV file available in our current working directory. This function takes the file name as an input and returns all the records present on it.
Let’s use our record.csv file to read records from it using read.csv() function.
Example
data <- read.csv("record.csv") print(data)
When we execute above code, it will give the following output
Output
Analyzing the CSV File
When we read data from the .csv file using read.csv() function, by default, it gives the output as a data frame. Before analyzing data, let’s start checking the form of our output with the help of is.data.frame() function. After that, we will check the number of rows and number of columns with the help of nrow() and ncol() function.
Example
csv_data<- read.csv("record.csv") print(is.data.frame(csv_data)) print(ncol(csv_data)) print(nrow(csv_data))
When we run above code, it will generate the following output:
Output
From the above output, it is clear that our data is read in the form of the data frame. So we can apply all the functions of the data frame, which we have discussed in the earlier sections.
Example: Getting the maximum salary
# Creating a data frame. csv_data<- read.csv("record.csv") # Getting the maximum salary from data frame. max_sal<- max(csv_data$salary) print(max_sal)
Output
Example: Getting the details of the person who have a maximum salary
# Creating a data frame. csv_data<- read.csv("record.csv") # Getting the maximum salary from data frame. max_sal<- max(csv_data$salary) print(max_sal) #Getting the detais of the pweson who have maximum salary details <- subset(csv_data,salary==max(salary)) print(details)
Output
Example: Getting the details of all the persons who are working in the IT department
# Creating a data frame. csv_data<- read.csv("record.csv") #Getting the detais of all the pweson who are working in IT department details <- subset(csv_data,dept=="IT") print(details)
Output
Example: Getting the details of the persons whose salary is greater than 600 and working in the IT department.
# Creating a data frame. csv_data<- read.csv("record.csv") #Getting the detais of all the pweson who are working in IT department details <- subset(csv_data,dept=="IT"&salary>600) print(details)
Output
Example: Getting details of those peoples who joined on or after 2014.
# Creating a data frame. csv_data<- read.csv("record.csv") #Getting details of those peoples who joined on or after 2014 details <- subset(csv_data,as.Date(start_date)>as.Date("2014-01-01")) print(details)
Output