0

Can someone please tell me how to get from dataframe df to the dataframe desired in the below reproducible code example, please? It is basically just a simple pivot. Thanks!

id <- c(1, 2)
x <- c('a', 'b')
y <- c('c', 'd')

df <- data.frame(id, x, y)

head(df)

c1 <- c('id', 'x', 'y')
c2 <- c('1', 'a', 'c')
c3 <- c('2', 'b', 'd')

desired <- data.frame(c1, c2, c3)

head(desired)

This seems to work (see also here):

test <- transpose(df)
colnames(test) <- rownames(df)
rownames(test) <- colnames(df)

but is it the best approach?

kath
  • 7,624
  • 17
  • 32
cs0815
  • 16,751
  • 45
  • 136
  • 299

1 Answers1

1

A one liner would be

setNames(data.frame(names(df), t(df)), paste0("c", 1:3))

A more general solution, without hardcoding the vector 1:3 is

setNames(data.frame(names(df), t(df)), paste0("c", seq_along(names(df))))
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66