[R] Programcode and data in the same textfile
Barry Rowlingson
B.Rowlingson at lancaster.ac.uk
Thu Jun 12 15:26:46 CEST 2003
> file = tmpfile, sep="\n")
> close(tmpfile)
> read.table(tmpfilename, header = TRUE)
>
Eurgh! Does R clean up tempfiles by itself?
Here's my idea. Just stick all the values in a vector, using
free-formatting to make it look nice, then reform it into a data frame:
indata <- function(x){
data <- c(
"Sex", "Id", "Age",
"Male", 1, 13.2,
"Female", 2, 8.1,
"Male", 3, 6.3,
"Male", 2, 12.2,
)
ncol <- 3
nrow <- length(data)/ncol
heads <- data[1:ncol];data <- data[-(1:ncol)]
asDF <- data.frame(matrix(data,ncol=ncol,byrow=T))
asDF[,2] <- as.numeric(asDF[,2])
asDF[,3] <- as.numeric(asDF[,3])
names(asDF) <- heads
asDF
}
Note that 'data' will be all character if there's any characters in
it, so you need to tweak the types with as.numeric or as.factor if thats
what you need. You could probably test if a column was all valid numbers
and automatically make it numeric, but then we're going a long way to
duplicating a lot of the code in read.table, which does something like
this (it uses 'scan()' to read from a file and then reforms it all into
a data frame).
All values must be comma separated and character values must be quoted.
Baz
More information about the R-help
mailing list