3

If I have a named vector and want to convert it into a dataframe, all functions I can think of construct it row-wise (i.e. it stacks name-value pairs on top of each other).

library(tibble)

x <- c(estimate = 0.595, ci.low = 0.110, ci.up = 2.004)

x
#> estimate   ci.low    ci.up 
#>    0.595    0.110    2.004

data.frame(x)
#>              x
#> estimate 0.595
#> ci.low   0.110
#> ci.up    2.004

as_tibble(x)
#> # A tibble: 3 x 1
#>   value
#>   <dbl>
#> 1 0.595
#> 2 0.11 
#> 3 2.00

enframe(x)
#> # A tibble: 3 x 2
#>   name     value
#>   <chr>    <dbl>
#> 1 estimate 0.595
#> 2 ci.low   0.11 
#> 3 ci.up    2.00

Created on 2021-03-29 by the reprex package (v1.0.0)

But I am looking for a function that does this column-wise. So the desired output looks something like the following:

foo(x)
#> # A tibble: 1 x 3
#> estimate   ci.low    ci.up 
#>   <dbl>    <dbl>    <dbl>
#>    0.595    0.110    2.004

Is there such a function? Or my only option is to just reshape the output from the functions mentioned above?

Indrajeet Patil
  • 4,673
  • 2
  • 20
  • 51

2 Answers2

6

You can transpose the vector and convert it into dataframe/tibble.

t(x) %>% as_tibble()
t(x) %>% data.frame()

#  estimate ci.low ci.up
#1    0.595   0.11 2.004
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
4

You can also convert to list first:

data.frame(as.list(x))
#   estimate ci.low ci.up
# 1    0.595   0.11 2.004

And if you want to be very efficient

data.table::setDF(as.list(x))
s_baldur
  • 29,441
  • 4
  • 36
  • 69