[R] Convert char vector to numeric table

james.holtman@convergys.com james.holtman at convergys.com
Tue Apr 1 02:22:59 CEST 2003

use 'textConnection':

> x.1 <- c('1 2 3','4 5 6','7 8 9','8 7 6','6 5 4')   # create character
> x.in <- textConnection(x.1) # setup connection
> x.data <- read.table(x.in)  # read in the character vector
> x.data
  V1 V2 V3
1  1  2  3
2  4  5  6
3  7  8  9
4  8  7  6
5  6  5  4

                      <mail at fwr.on.ca>             To:       "R's help mailing list" <r-help at stat.math.ethz.ch>                            
                      Sent by:                     cc:                                                                                     
                      r-help-bounces at stat.m        Subject:  [R] Convert char vector to numeric table                                      
                      03/31/03 17:09                                                                                                       
                      Please respond to                                                                                                    

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:


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)

Am I missing something?

Bruce L.

R-help at stat.math.ethz.ch mailing list

"NOTICE:  The information contained in this electronic mail transmission is
intended by Convergys Corporation for the use of the named individual or
entity to which it is directed and may contain information that is
privileged or otherwise confidential.  If you have received this electronic
mail transmission in error, please delete it from your system without
copying or forwarding it, and notify the sender of the error by reply email
or by telephone (collect), so that the sender's address records can be

More information about the R-help mailing list