[R] Convert char vector to numeric table
Prof. Brian Ripley
ripley at stats.ox.ac.uk
Tue Apr 1 08:41:36 CEST 2003
Use a file() connection (no argument) or a textConnection.
file() is a powerful tool, often overlooked.
On Mon, 31 Mar 2003, Nurnberg-LaZerte wrote:
> I'm a great fan of read.table(), but this time the data had a lot of cruft. So I used readLines() and editted the char vector to eventually get something like this:
> " 23.4 1.5 4.2"
> " 19.1 2.2 4.1"
> and so on. To get that into a 3 col numeric table, I first just used:
>
> writeLines(data,"tempfile")
> read.table("tempfile",col.names=c("A","B","C"))
>
> Works fine, but writing to a temporary file seems ... inelegant? And read.table() doesn't take a char vector as a file or connection argument. The following works but it seems like a lot of code:
>
> data <- sub(" +","",data) # remove leading blanks for strsplit
> data <- strsplit(data," +") # strsplit returns a list of char vectors
> ndata <- character(0) # vectorize the list of char vectors
> for (ii in 1:length(data)) ndata <- c(ndata,data[[ii]])
> ndata <- as.numeric(ndata)
> dim(ndata) <- c(3,length(data))
> data <- t(ndata)
> data.frame(A=data[,1],B=data[,2],C=data[,3])
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list