Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Named Character Vector to data.frame

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 
like image 537
Tyler Muth Avatar asked May 29 '13 14:05

Tyler Muth


People also ask

How do you turn a vector into a Tibble R?

Use as_tibble() to turn an existing object into a tibble. Use enframe() to convert a named vector into a tibble.

What does Tibble :: Enframe () do?

enframe() converts a named vector to a tib- ble with a column of names and column of values.


2 Answers

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).

like image 126
Matthew Plourde Avatar answered Sep 24 '22 03:09

Matthew Plourde


The answers from @MatthewPlourde and @JackRyan work, but if you have a long named vector it is annoying to have a data frame with one row and many columns. If you'd rather have a "key" column and a "value" column with many rows, any of the following should work:

data.frame(keyName=names(testVect), value=testVect, row.names=NULL)  ##        keyName      value ## 1   db_version 11.2.0.3.0 ## 2 elapsed_time      12.89 ## 3     cpu_time      12.71   ## Suggested by @JWilliman tibble::enframe(testVect)  ## # A tibble: 3 x 2 ##   name         value ##   <chr>        <chr> ## 1 db_version   11.2.0.3.0 ## 2 elapsed_time 12.89 ## 3 cpu_time     12.71   ## Suggested by @Joe stack(testVect) ##       values          ind ## 1 11.2.0.3.0   db_version ## 2      12.89 elapsed_time ## 3      12.71     cpu_time 
like image 32
dnlbrky Avatar answered Sep 26 '22 03:09

dnlbrky