Convert Named Character Vector to data.frame

Tyler Muth picture Tyler Muth · May 29, 2013 · Viewed 67.8k times · Source

I have a named character vector returned from xmlAttrs like this:

testVect <- structure(c("11.2.0.3.0", "12.89", "12.71"), .Names = c("db_version", 
             "elapsed_time", "cpu_time"))

I would like to convert it to a data frame that looks like this:

testDF <- data.frame("db_version"="11.2.0.3.0","elapsed_time"=12.89,"cpu_time"=12.71)
head(testDF)
  db_version elapsed_time cpu_time
1 11.2.0.3.0        12.89    12.71

Answer

Matthew Plourde picture Matthew Plourde · May 29, 2013

It's as simple as data.frame(as.list(testVect)). Or if you want sensible data types for your columns, data.frame(lapply(testVect, type.convert), stringsAsFactors=FALSE).