library(tibble)
# create a named vector<- c(apple = 5, peach = 7, melon = 9) x
# turn named vector to a two-column tibbleenframe(x)
Output:
# A tibble: 3 × 2
name value
<chr> <dbl>
1 apple 5
2 peach 7
3 melon 9
enframe()
converts a named atomic vector to a two-column tibble: the first column records the name of the elements in the vector, and the second column records the element values in the vector.
library(tibble)
# create a named vector<- c(apple = 5, peach = 7, melon = 9) x
# turn named vector to a two-column tibbleenframe(x)
Output:
# A tibble: 3 × 2
name value
<chr> <dbl>
1 apple 5
2 peach 7
3 melon 9
If the vector is not named, then a natural numeric sequence is used to create the name
column.
enframe(c(1, 3, 6, 19))
Output:
# A tibble: 4 × 2
name value
<int> <dbl>
1 1 1
2 2 3
3 3 6
4 4 19
Use name = NULL
to turn off the name
column. This creates a tibble with a single column.
enframe(c(1, 3, 6, 19), name = NULL)
Output:
# A tibble: 4 × 1
value
<dbl>
1 1
2 3
3 6
4 19
You can use enframe()
to convert a named list to a tibble in a similar way. The result will be a nested tibble with a column of type list. For unnamed vectors, the natural sequence is used as the name
column.
# create a named list<- list(Mike = .1, Tom = 2:3, Jane = c("x", "y", "z")) a a
Output:
$Mike
[1] 0.1 $Tom
[1] 2 3 $Jane
[1] "x" "y" "z"
# convert the list to a tibbleenframe(a)
Output:
# A tibble: 3 × 2
name value
<chr> <list>
1 Mike <dbl [1]>
2 Tom <int [2]>
3 Jane <chr [3]>