Open In App

Writing to CSV files in R

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:

Let us first create a data frame.

Example:




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:

Our Data in console

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

Example:




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


Article Tags :