Skip to content
Prev 304576 / 398503 Next

apply --> data.frame

Here are two ways of turning a character vector like yours into a data.frame,
neither of which uses an apply-like function.
  > s <- c(XVI="p,16", XVII="q,17", XVIII="r,18")
  > d1 <- data.frame(Letter=sub(",.*", "", s), Number=as.integer(sub(".*,","",s)))
  > d2 <- read.table(text=s, sep=",", col.names=c("Letter","Number"), row.names=names(s))
  > d1
        Letter Number
  XVI        p     16
  XVII       q     17
  XVIII      r     18
  > all.equal(d1, d2)
  [1] TRUE

I don't agree with your analysis of what went wrong with your example
  > z0 <- as.data.frame(t(sapply(c("a,1","b,2","c,3"),function (n) strsplit(n,",")[[1]])))
  > str(z0)
  'data.frame':   3 obs. of  2 variables:
   $ V1: Factor w/ 3 levels "a","b","c": 1 2 3
    ..- attr(*, "names")= chr  "a,1" "b,2" "c,3"
   $ V2: Factor w/ 3 levels "1","2","3": 1 2 3
    ..- attr(*, "names")= chr  "a,1" "b,2" "c,3"
You wrote
The "numbers" 1,2,3 were always considered to be strings, because
strsplit() takes strings, like "a,1", and returns a list of vectors of strings,
like list(c("a","1")).  The c() function has nothing to do with it.

Functions like read.table() will guess when it is appropriate to convert things
from strings to numbers, but most times you have to do the conversion explicitly.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com