R Program to Write to a File

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Example 1: Write a Sentence to txt File in R

sentence1 <- "Data Science is fun"

# use writeLines() to write to txt file
writeLines(sentence1, "file1.txt")

In the above example, we have used the writeLines() function to write the string named sentence1 to a txt file. Notice the arguments passed inside writeLines(),

writeLines(sentence1, "file1.txt")

Here,

  1. sentence1 - name of the string we want to export
  2. file1.txt - name of the txt file

Our file1.txt would look like this:

Note: If the file is in some other location, we have to specify the path along with the file name as: writeLines("D:/folder1/file1.txt").


Example 2: Write Into CSV File in R

# Create a data frame
dataframe1 <- data.frame (
  Name = c("Juan", "Alcaraz", "Simantha"),
  Age = c(22, 15, 19),
  Vote = c(TRUE, FALSE, TRUE))

# write dataframe1 into file1 csv file
write.csv(dataframe1, "file1.csv")

In the above example, we have used the write.csv() function to export a dataframe named dataframe1 to a CSV file. Notice the arguments passed inside write.csv(),

write.csv(dataframe1, "file1.csv")

Here,

  1. dataframe1 - name of the data frame we want to export
  2. file1.csv - name of the csv file

Finally, the file1.csv file would look like this in our directory:

To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)