15.1 Creating a Data Frame
15.1.1 Problem
You want to create a data frame from vectors.
15.1.2 Solution
You can put vectors together in a data frame with data.frame():
# Two starting vectors
g <- c("A", "B", "C")
x <- 1:3
dat <- data.frame(g, x)
dat
#> g x
#> 1 A 1
#> 2 B 2
#> 3 C 315.1.3 Discussion
A data frame is essentially a list of vectors and factors. Each vector or factor can be thought of as a column in the data frame.
If your vectors are in a list, you can convert the list to a data frame with the as.data.frame() function:
lst <- list(group = g, value = x) # A list of vectors
dat <- as.data.frame(lst)The tidyverse way of creating a data frame is to use data_frame() or as_data_frame() (note the underscores instead of periods). This returns a special kind of data frame – a tibble – which behaves like a regular data frame in most contexts, but prints out more nicely and is specifically designed to play well with the tidyverse functions.
data_frame(g, x)
#> Warning: `data_frame()` is deprecated as of tibble 1.1.0.
#> Please use `tibble()` instead.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_warnings()` to see where this warning was generated.
#> # A tibble: 3 x 2
#> g x
#> <chr> <int>
#> 1 A 1
#> 2 B 2
#> 3 C 3# Convert the list of vectors to a tibble
as_data_frame(lst)A regular data frame can be converted to a tibble using as_tibble():
as_tibble(dat)
#> # A tibble: 3 x 2
#> group value
#> <chr> <int>
#> 1 A 1
#> 2 B 2
#> 3 C 3