Open In App

Writing to CSV files in R

Last Updated : 26 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

For Data Analysis sometimes creating CSV data file is required and do some operations on it as per our requirement. So, In this article we are going to learn that how to write data to CSV File using R Programming Language.

To write to csv file write.csv() function is used.

Syntax: write.csv(data, path)

Parameter:

  • data: data to be added to csv
  • path: pathname of the file

Approach:

  • Create a DataFrame
  • Pass required values to the function
  • Write to file

Let us first create a data frame.

Example:

R




Country <- c("China", "India", "United States", "Indonesia", "Pakistan")
  
Population_1_july_2018 <- c("1,427,647,786", "1,352,642,280"
                            "327,096,265", "267,670,543", "212,228,286")
  
Population_1_july_2019 <- c("1,433,783,686", "1,366,417,754"
                            "329,064,917", "270,625,568", "216,565,318")
  
change_in_percents <- c("+0.43%", "+1.02%", "+0.60%", "+1.10%", "+2.04%")
  
  
data <- data.frame(Country, Population_1_july_2018, Population_1_july_2019, change_in_percents)
print(data)


Output:

data in console

Our Data in console

Now let us write this data to a csv file and save it to a required location.

Example:

R




Country <- c("China", "India", "United States", "Indonesia", "Pakistan")
  
Population_1_july_2018 <- c("1,427,647,786", "1,352,642,280"
                            "327,096,265", "267,670,543", "212,228,286")
  
Population_1_july_2019 <- c("1,433,783,686", "1,366,417,754"
                            "329,064,917", "270,625,568", "216,565,318")
  
change_in_percents <- c("+0.43%", "+1.02%", "+0.60%", "+1.10%", "+2.04%")
  
  
data <- data.frame(Country, Population_1_july_2018, Population_1_july_2019, change_in_percents)
print(data)
  
write.csv(data,"C:\\Users\\...YOUR PATH...\\population.csv")
print ('CSV file written Successfully :)')


Output:

CSV file with data

CSV File with data



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads