postylem
postylem

Reputation: 1121

how to coerce a vector into a tibble?

What is the 'right' way to coerce a vector into a tibble? I'm trying to use the tidyverse, and there seems to be a hole in it.

Say I have a vector that I want to turn into a tibble with one row (cf. one column). According to the documentation for tibble I should be able to use as_tibble_row() (cf. as_tibble_col() or as_tibble_column() *). However, when I try to call these functions, it seems they do not exist. I have installed and imported tidyversev3.0.1 (which contains tibble v2.1.3).

> as_tibble_row(c(a = 1, b = 2))
Error in as_tibble_row(c(a = 1, b = 2)) : 
  could not find function "as_tibble_row"
> as_tibble_col(c(a = 1, b = 2))
Error in as_tibble_col(c(a = 1, b = 2)) : 
  could not find function "as_tibble_col"
> as_tibble_column(c(a = 1, b = 2))
Error in as_tibble_column(c(a = 1, b = 2)) : 
  could not find function "as_tibble_column"

likewise ??as_tibble_row, ??as_tibble_col, ??as_tibble_column find no results.

When I try just the simple as_tibble(), it gives me a tibble column, but I get a warning

> as_tibble(c(a = 1, b = 2))
# A tibble: 2 x 1
  value
  <dbl>
1     1
2     2
Warning message:
Calling `as_tibble()` on a vector is discouraged, 
because the behavior is likely to change in the future. 
Use `tibble::enframe(name = NULL)` instead.

Using enframe() as suggested gives the expected result for a column:

> tibble::enframe(c(a = 1, b = 2))
# A tibble: 2 x 2
  name  value
  <chr> <dbl>
1 a         1
2 b         2

But I still don't know how to coerce the vector into a single row. What am I missing (perhaps the documentation needs to be updated, because it seems to reference these functions which don't seem to exist)?


*the described function for the column version in the documentation refers to it as as_tibble_column() in the description but as as_tibble_col() elsewhere...

Upvotes: 2

Views: 394

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226087

The documentation you're pointing to refers to version 3.0.1 of the package (you say you're using 2.1.3):

enter image description here

> as_tibble_col(c(a = 1, b = 2))
# A tibble: 2 x 1
  value
  <dbl>
1     1
2     2
> as_tibble_row(c(a = 1, b = 2))
# A tibble: 1 x 2
      a     b
  <dbl> <dbl>
1     1     2

The NEWS file says that these functions were added in version 3.0.0.

Upvotes: 4

John Garland
John Garland

Reputation: 513

I think

as_tibble(t(c(a = 1, b = 2)))

is what you are looking for (though you don't actually specify the exact desired output here).

> as_tibble(t(c(a = 1, b = 2)))
# A tibble: 1 x 2
      a     b
  <dbl> <dbl>
1     1     2

Upvotes: 3

Related Questions