0

Is there a convenient way to create a data frame from a vector and using the values of the vector as column names? Result should only have 1 row with empty fields. Values in vector may vary.

Given:

x <- c("1","2","3")

Output:

# A tibble: 1 x 3
  `1`   `2`   `3`  
  <chr> <chr> <chr>
1 ""    ""    ""  
Dutschke
  • 277
  • 2
  • 15
  • 1
    Does this answer your question? [Initialize an empty tibble with column names and 0 rows](https://stackoverflow.com/questions/48833807/initialize-an-empty-tibble-with-column-names-and-0-rows) – Giora Simchoni Dec 13 '21 at 09:56

3 Answers3

3

If you're a tidyverse fan as I see by your using of tibble, you could use a combination of map_dfc and setNames:

library(tidyverse)

df <- x %>% map_dfc(setNames, object = list(character(1)))

df
# A tibble: 1 x 3
 `1`   `2`   `3`  
 <chr> <chr> <chr>
1 ""    ""    "" 
Giora Simchoni
  • 3,487
  • 3
  • 34
  • 72
  • I like tidyverse, and your answer looks good to me, but its mising the 1 row with empty ("") fields. – Dutschke Dec 13 '21 at 09:56
1

Try this:

x = c("1","2","3")

df = data.frame(matrix(ncol = 3, nrow = 0))
names(df) = x

Output:
> df
[1] 1 2 3

> str(df)
'data.frame':   0 obs. of  3 variables:
 $ 1: logi 
 $ 2: logi 
 $ 3: logi 

Update:

df = data.frame(matrix(ncol = 3, nrow = 1))
colnames(df) = x
> df
   1  2  3
1 NA NA NA
Marco_CH
  • 3,243
  • 8
  • 25
  • Not 100% what i wanted but i can work with that, so thank you! – Dutschke Dec 13 '21 at 09:49
  • I just updated it, now it's with a first empty row. Does this help? If you need "" instead of NA, you could add `df[is.na(df)] = ""`. – Marco_CH Dec 13 '21 at 09:54
  • This would work, thank you! The other answer is a bit more compact, so i have to give the accepted answer to that one. – Dutschke Dec 13 '21 at 09:59
1

You can use pivot_wider:

library(tidyr)
data.frame(x) %>%
  pivot_wider(x, 
              names_from = x, values_from = x,
              values_fn = function(x) "")
# A tibble: 1 × 3
  `1`   `2`   `3`  
  <chr> <chr> <chr>
1 ""    ""    ""   
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34