2

I built the following R script to take a .csv generated by an automated report and split it into several .csv files.

This code works perfectly, and outputs a .csv file for each unique value of "facility" in "todays_data.csv":

disps <- read.csv("/Users/me/Downloads/todays_data.csv", header = TRUE, sep=",")
for (facility in levels(disps$Facility)) {
temp <- subset(disps, disps$Facility == facility & disps$Alert.End == "")
temp <- temp[order(temp$Unit, temp$Area),]
fn <- paste("/Users/me/Documents/information/", facility, "_todays_data.csv", sep = "")
write.csv(temp, fn, row.names=FALSE)
}

But this does not output anything:

args <- commandArgs(trailingOnly = TRUE)
file <- args[1]
disps <- read.csv(file, header = TRUE, sep=",")
for (facility in levels(disps$Facility)) {
temp <- subset(disps, disps$Facility == facility & disps$Alert.End == "")
temp <- temp[order(temp$Unit, temp$Area),]
fn <- paste("/Users/me/Documents/information/", facility, "_todays_data.csv", sep = "")
write.csv(temp, fn, row.names=FALSE)
}

The only difference between the two files is that the first hardcodes the path to the .csv file to be split, while the second one has it passed as an argument in the command line using Rscript.

The read.csv() command works with the passed file path, because I can successfully run commands like head(disps) while running the script via Rscript.

Nothing within the for-loop will execute when run via Rscript, but things before and after it will.

Does anyone have any clues as to what I've missed? Thank you.

  • 1
    The subset function is dangerous (as described in its help page) and you have magnified that danger by using incorrectly. In interactive use this would be the correct code: `subset(disps, Facility == facility & Alert.End == "")`. My advice would be to use "[[" instead of subset when doing any sort of programming. – IRTFM May 15 '14 at 20:01
  • Well, why don't you take a look at what's actually in `file` to verify that it is a character string with the proper path? – Carl Witthoft May 15 '14 at 20:06
  • @CarlWitthoft I didn't include it, but I executed: head(disps) within the Rscripts version, and got the values I expected. That's why I know the .csv path is being ported correctly. – user3542251 May 15 '14 at 20:19
  • Looking at your code and trusting what you say, the only possible reason I see is that you file must be missing a `Facility` column. Try to add `stopifnot("Facility" %in% names(disps))` before the loop and see what you get. – flodel May 15 '14 at 20:51
  • Also, are you sure that `Facility` is a factor? If it is coded as an integer or character, for instance, the levels will be `NULL` – John Paul May 15 '14 at 21:28
  • Well, it couldn't be a character vector, since stringsAsFactors=TRUE by default but it could be a numeric or integer value. Perhaps trying `for( facility in unique(as.character(disps$Facility)) )` – IRTFM May 15 '14 at 23:40

0 Answers0