Home > Software design >  How to create a one-row data.frame (tibble) from 2 vectors. One with the desired column names, and a
How to create a one-row data.frame (tibble) from 2 vectors. One with the desired column names, and a

Time:11-09

I have two character vectors in R of the same size. Let's call them variables and values (they have the same number of elements).

I wish to create a one-row data.frame (tibble) from these 2 vectors. Where the column names are variables and he actual values in the rows are values.

How can I do this?

CodePudding user response:

library(tidyverse)

variables <- letters[1:3]
variables
#> [1] "a" "b" "c"

values <- seq(3)
values
#> [1] 1 2 3

data.frame(variables, values) %>%
   pivot_wider(names_from = variables, values_from = values)
#> # A tibble: 1 x 3
#>       a     b     c
#>   <int> <int> <int>
#> 1     1     2     3

Created on 2021-11-08 by the reprex package (v2.0.1)

CodePudding user response:

You can create a named vector and splice it for use with tibble().

values <- 1:3
variables <- LETTERS[1:3]

library(tibble)

tibble(!!!setNames(values, variables))

# A tibble: 1 x 3
      A     B     C
  <int> <int> <int>
1     1     2     3
  • Related