4

Lets say i have the following data: x <- 1:2.

My desired output is a data.frame() like the following:

a b
1 2

With base R i would do something along:

df <- data.frame(t(x))
colnames(df) <- c("a", "b")

Question: How would i do this with the pipe operator?

What i tried so far:

library(magrittr)
x %>% data.frame(a = .[1], b = .[2])
Tlatwork
  • 1,445
  • 12
  • 35
  • 4
    Some base R options: `as.data.frame.list(x, col.names = c("a","b"))` or `setNames(as.data.frame.list(x), c("a","b"))` – Jaap Sep 29 '19 at 17:22
  • 1
    You were almost there: `library(magrittr); x %>% t() %>% data.frame() %>% set_names(c("a", "b"))`. The function `set_names` is from the `magrittr` package and can be replaced by `setNames` or `colnames<-` (enclosed in backticks). – Uwe Sep 30 '19 at 14:00

1 Answers1

4

After the transpose, convert to tibble with as_tibble and change the column names with set_names

library(dplyr)
library(tibble)
x %>% 
  t %>%
  as_tibble(.name_repair = "unique") %>%
  setNames(c("a", "b"))
# A tibble: 1 x 2
#      a     b
#  <int> <int>
#1     1     2

Or another option if we want to use the OP's syntax would be to wrap the code with {}

x %>%
     {data.frame(a = .[1], b = .[2])} 
Uwe
  • 41,420
  • 11
  • 90
  • 134
akrun
  • 874,273
  • 37
  • 540
  • 662