I am reading in a file in SPSS format (.por), cleaning it in R and then exporting as a clean .csv file. Is it possible to save the code I am using to read/clean/export the data to save it along with the data? In other words, I want to be able to load the datafile at some later point and be able to recall exactly how it was created.
2 Answers
Just save a set of files, a .R file with the R code, the por file with the SPSS data, and a csv file with the data, all starting with the same name:
spam.R
spam.por
spam.csv
To transport them, you could zip these files into spam.zip.
Alternatively, you could add the R code as comments above the data:
# here R code
# Some more code
here the csv data
read.table will automatically skip these lines as they start with a # (the standard comment character of read.csv).
1 Comment
If you want to do it all from the console, here's a hack:
foo<-attributes(myfunc)$srcref
write.table(as.character(foo),'myfunc.txt')
Edit: to answer Paul's question, here's the output from one of my 'toys' . The elements of each row (one element per pair of quotation marks) are tab-separated.
"x"
"1" "function(x, numdig=3, na.rm=TRUE,printit=TRUE)"
"2" "{"
"3" " x<-as.vector(x)"
"4" " if (na.rm) x <- x[!is.na(x)]"
"5" " skewx<-theskew(x)"
"6" " kurtosisx<-thekurt(x)"
"7" " #allstats<-list(min=min(x), max=max(x), mean=mean(x), median=median(x),sdev=sd(x), skew=theskew(x), kurtosis=thekurt(x))"
"8" " #looks nicer w/ dataframe rather than pure list"
"9" " allstats<-data.frame(cbind(min=min(x), max=max(x), mean=mean(x), median=median(x),sdev=sd(x), skew=theskew(x), kurtosis=thekurt(x)),row.names='')"
"10" " #too long for one line"
"11" " if(printit)"
"12" " {"
"13" " print(format(allstats[1:4],digits=numdig))"
"14" " print(format(allstats[5:7],digits=numdig))"
"15" " }"
"16" " return(invisible(allstats))"
"17" " }"
I have not tried to find a console hack to convert that text back into function code, but I bet a simple gsub('"','',textobject[,2]) would work.
2 Comments
attributes to retrieve some of the information "included" in any closure, aka function, object. In this case, the attribute "srcref" contains the source code for the function. Welcome to Object-Oriented Programming! :-)