How To Output Your Work to Text File in R (With Examples)

When people talk about the R programming language it’s usually in terms of direct problem-solving. Discussions of R might touch on classic combinatorial optimization challenges like the Traveling Salesman Problem. Or it could look at optimal methods of sorting huge datasets to discover specific patterns. But the R programming language has all of the features found in more desktop-oriented languages. And this includes access to the underlying operating system along with standard file manipulation. In fact, you might be surprised to find that R actually makes it easier to work with files than many languages that are specifically desktop-focused. For example, you can easily take the data you’re working with in R and output that work into a text file.

R, Files, and File Systems

At this point you’re probably considering the concept of R’s relationship to files in one of two ways. You’re either impressed at the idea of simple file access or wondering why that should be impressive. To clarify both of these positions we need to consider exactly how R functions.

R is an interpreted language whose platform, including Comprehensive R Archive Network (CRAN) access, is maintained on Windows, OSX, and Linux. R also supports both x86-64 and Arm processors. It’s important to keep in mind that all three of these operating systems have significant differences in their underlying structure. OSX and Linux do have a number of similarities. But even there the underlying file system is typically quite different. And Windows is also different from OSX and Linux in terms of both the operating system design and primary file system.

This means that when R needs to create or modify a text file it needs to automatically compensate for all of the quirks present in every supported operating system. This is usually done in a totally automated fashion. But there’s one significant hiccup – paths. For example, consider the following path written in the Windows format.

\this\Is\our\path\ourData.csv

Windows isn’t case-sensitive so we could also write it like this.

\this\is\our\path\ourData.csv

But Linux is case-sensitive so the “Is” and “is” would be seen as designating something totally distinct from each other. Not to mention that Linux and OSX use a forward slash to indicate directory structure and paths. So under those operating systems, we’d want things formatted like the following.

/this/is/our/path/ourData.csv

Interestingly enough, Windows does understand the Unix paths utilized by OSX and Linux. So it’s generally safe to just default to that format. And we can also just write to the current directory without bothering to use a path at all. If we just pass a file name to R, like ourData.csv, there won’t be any problems with path resolution. But the best way to safeguard against path issues when working with files in R is to use the normalizePath function. We leverage it in the following manner.

normalizePath(“\this\Is\our\path\ourData.csv”)

The function would return the proper formatting for whatever operating system we’re currently using. And if we used the script on another operating system it’d adapt to that environment as well. For the sake of simplicity, we’ll just be writing text files to the working directory that we’re running the R script from. But keep the path resolution issue in mind if you build on these examples for your own use. With all that in mind, get ready to be amazed by how well R handles everything else related to file access.

Basic Text Files and Data Handling

We can begin with a simple example. Try running the following code.

ourDataFrame <- data.frame(
Planet <- c(“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”,”Saturn”),
Type <- factor(c(“Terrestrial”, “Terrestrial”, “Terrestrial”,
“Terrestrial”, “Gas”, “Gas”)),
Distance <- c(35000000,67000000,93000000,
142000000,484000000,889000000 ),
Circumference <- c(9522,23617,24889,13256,278985,235185)
)

print(ourDataFrame)

In this simple example, we create a data frame called ourDataFrame. We then populate it with some basic information about some of the planets in the solar system. Then we print the contents of that variable to the screen. Here’s what’s so amazing about R’s file manipulation. We can write some data to a file with almost the same methodology that we use to write to the screen. Try replacing the print statement with the following.

write.csv(ourDataFrame, file = “ourCSV.csv”)

The only real difference between writing that data to screen and to csv file is the fact that we need to provide a file name for the csv. If you open this file in a text editor you’ll see that it’s essentially just a text file with the data stored as comma-separated values.

Writing, Reading, and Some More Advanced Functionality

While the previous example was easy to set up, you might be wondering about more advanced usage. Take a look at the following code that expands on our previous work.

ourDataFrame <- data.frame(
Planet <- c(“Mercury”, “Venus”, “Earth”, “Mars”, “Jupiter”,”Saturn”),
Type <- factor(c(“Terrestrial”, “Terrestrial”, “Terrestrial”,
“Terrestrial”, “Gas”, “Gas”)),
Distance <- c(35000000,67000000,93000000,
142000000,484000000,889000000 ),
Circumference <- c(9522,23617,24889,13256,278985,235185)
)

ourFileName <- “ourCSV.csv”
print(ourDataFrame[3,1])
write.csv(ourDataFrame, file = ourFileName, row.names = FALSE)
ourDataFrameRead <- read.csv(file = ourFileName)
print(ourDataFrameRead[3,1])

In this example, we begin by defining the same data frame. We also define a new variable called ourFileName. This will simplify things when we need to refer to ourCSV.csv more than once. Next, we print out the 3,1 position in ourDataFrame – “Earth”. We proceed to write our data frame to a file with the name specified in ourFileName. The only difference in our formatting comes from the fact that we’re excluding row names. Next, we use the flip side of the write.csv function – read.csv. We load ourFileName into ourDataFrameRead. And, finally, we print out the 3,1 position in ourDataFrameRead. Note that we get the same value printing that position in ourDataFrame and ourDataFrameRead. We’ve preserved our data when writing it to file and when reading it into a new variable.

But we don’t need to limit ourselves to data frames. We can even write plain text to a text file. For example, we might want to output status updates. Take a look at the following example.

writeLines(c(“Week 1 batch finished”,”Successful”, 44343), “status_week_1.txt”)

In this example, we use the writeLines function to output text to the second argument provided to it. The first argument consists of the values we want to output. In this case we’re using two strings to indicate status and a number that represents a theoretical classification.

As you can see, R makes it easy to approach writing to a text file in multiple ways. We have an easy way to write basic data to a text file. Likewise, an equally easy way to write out complex variables to text files and read them back in to a new variable as needed.

Scroll to top
Privacy Policy