A quick function for editing CSV files in R

[This article was first published on Noam Ross - R, 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.

I’ve been hunting for a lightweight CSV editor for OSX so I could to make fixes to data files and not need to fire up Excel. While you can edit a CSV file in any text editor, it’s a pain to navigate the files without a spreadsheet-like interface. Unfortunately there doesn’t seem to be a good, free option out there.

Today I remembered R has a native XCode editor for editing data frames, and I realized I could write a function that would load the CSV as a data frame, let me edit it, then close and save it in CSV format again. Here’s the function. This is now part of my .Rprofile file, and makes tweaking data files a snap:

#' Use the data editor for a CSV file
#' 
#' This function loads a CSV file, lets the user edit it in the native data
#' editor, then re-saves it, prompting the user for a new file name if 
#' desired.
#' 
fix.csv <- function(file, new.name=TRUE, sep=",", comment.char="") {
  tmpframe <- read.csv(file, sep=sep,quote="", colClasses="character",
                       stringsAsFactors=FALSE, comment.char="",
                       blank.lines.skip=FALSE, na.strings="")
  tmpframe <- edit(tmpframe)
  if(is.character(new.name)) {
    out.name <- new.name
  } else if(new.name <- TRUE) {
    out.name <- readline(prompt="Enter file name to save (Hit enter to use original):")
  } else {
    out.name <- file
  }
  if(out.name=="") out.name <- file
  write.table(tmpframe, file=out.name, append=FALSE, quote=FALSE, sep=sep,
              row.names=FALSE)
}

Here it is as a gist

This works in RStudio my Mac but unfortunately not when I’m working on my server, because RStudio server doesn’t support a data editor. (I know it’s been requested a few times - let’s hope they add it in!)

Update:" David Harris notes that “if you try this on a Mountain Lion Mac without X11/XQuartz, it will cause a fatal error.”

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

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)