首页 > 解决方案 > 将向量按列转换为数据框

问题描述

如果我有一个命名向量并想将其转换为数据框,我能想到的所有函数都按构造它(即,它将名称-值对堆叠在一起)。

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

reprex 包于 2021-03-29 创建(v1.0.0)

但我正在寻找一个可以执行此的函数。因此,所需的输出如下所示:

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

有这样的功能吗?或者我唯一的选择是仅仅重塑上述函数的输出?

标签: r

解决方案


您可以转置向量并将其转换为数据帧/小标题。

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

#  estimate ci.low ci.up
#1    0.595   0.11 2.004

推荐阅读