library(tibble)
# Create a named vector of fruit sales<- c(apples = 50, oranges = 30, bananas = 20, grapes = 40) s
# turn the vector to a single-column tibbleas_tibble_col(s)
Output:
# A tibble: 4 × 1
value
<dbl>
1 50
2 30
3 20
4 40
as_tibble_col()
turns a vector or list to a single-column tibble.as_tibble_row()
turns a vector or list to a single-row tibble.as_tibble_col()
converts a vector to a single-column tibble.
library(tibble)
# Create a named vector of fruit sales<- c(apples = 50, oranges = 30, bananas = 20, grapes = 40) s
# turn the vector to a single-column tibbleas_tibble_col(s)
Output:
# A tibble: 4 × 1
value
<dbl>
1 50
2 30
3 20
4 40
Use argument column_name
to specify the column name.
# rename column as 'sales'as_tibble_col(s, column_name = "sales")
Output:
# A tibble: 4 × 1
sales
<dbl>
1 50
2 30
3 20
4 40
Names of the vector elements (if any) are dropped from the tibble output. If you wish to reserve the names of the vector elements, use enframe()
instead.
enframe(s, name = "fruit", value = "sales")
Output:
# A tibble: 4 × 2
fruit sales
<chr> <dbl>
1 apples 50
2 oranges 30
3 bananas 20
4 grapes 40
You can also use as_tibble_col()
to convert a list to a one-column tibble, with the column being a list-column.
<- list( L name = "John", age = 30, married = TRUE, children = list(c("Alice", "Bob")))
as_tibble_col(L, column_name = "person")
Output:
# A tibble: 4 × 1
person
<named list>
1 <chr [1]>
2 <dbl [1]>
3 <lgl [1]>
4 <list [1]>
You can use deframe()
to turn the output back to list; that is, L
is identical to as_tibble_col(L) %>% deframe()
.
Opposite to as_tibble_col()
, the function as_tibble_row()
turns a vector or list into a single-row tibble, using names of the elements as the column names, and values of the elements as values in the first row.
# convert a vector to one-row tibbleas_tibble_row(s)
Output:
# A tibble: 1 × 4
apples oranges bananas grapes
<dbl> <dbl> <dbl> <dbl>
1 50 30 20 40
# convert a list to one-row tibbleas_tibble_row(L)
Output:
# A tibble: 1 × 4
name age married children
<chr> <dbl> <lgl> <list>
1 John 30 TRUE <chr [2]>