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,
- sentence1 - name of the string we want to export
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,
- dataframe1 - name of the data frame we want to export
file1.csv
- name of the csv file
Finally, the file1.csv
file would look like this in our directory: