rcorty rcorty - 3 months ago 17
R Question

How can I make a tibble/tbl_df/data_frame from a vector or vectors

I have a name and a vector

my.name <- 'data.values'
my.vec <- 1:5


and I'd like to make a tibble/tbl_df/data_frame with one column that has
my.name
as the name of that column and
my.vec
as the values. What I have is

df <- data_frame(placeholder = rep(NA, length(my.vec)))
df[[my.name]] <- my.vec
df[['placeholder']] <- NULL


Which just feels silly. Is there an easier way to do this?

I am also interested in the case where I have multiple vectors and multiple names, e.g.

my.name1 <- 'data.values.day1'
my.name2 <- 'data.values.day2'
my.vec1 <- 1:5
my.vec2 <- 2:6
...

Answer

You can create a data_frame first and then set its column names:

my.data <- data_frame(my.vec.1, my.vec.2, ...)
names(my.data) <- c(my.name.1, my.name.2, ...) # Order is important here
Comments