Tiago Bruno
Tiago Bruno

Reputation: 413

Transform rows into columns, make repeated column names with suffix based on another column

I have a dataframe in the format:

df1    <- data.frame(x = c(1,2), y = c(5,6), z = c(7,8), names = c("A","B"))

  x y z names
1 1 5 7     A
2 2 6 8     B

What is the best way to transform this df1 into this:

data.frame(x.A = 1, x.B = 2, y.A = 5, y.B = 6, z.A = 7, z.B = 8)

  x.A x.B y.A y.B z.A z.B
1   1   2   5   6   7   8

Upvotes: 2

Views: 98

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 102299

A base R option

> data.frame(t(unlist(Map(setNames, df1[setdiff(names(df1), "names")], df1["names"]))))
  x.A x.B y.A y.B z.A z.B
1   1   2   5   6   7   8

Upvotes: 0

Yuriy Saraykin
Yuriy Saraykin

Reputation: 8880

library(tidyverse)
df <- data.frame(x = c(1,2), y = c(5,6), z = c(7,8), names = c("A","B"))
pivot_longer(df, -names) %>% 
  unite(Var, c(names, name), sep = ".") %>% 
  mutate(id = 1) %>% 
  pivot_wider(id, names_from = Var, values_from = value) %>% 
  select(-id)
#> # A tibble: 1 x 6
#>     A.x   A.y   A.z   B.x   B.y   B.z
#>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1     1     5     7     2     6     8

Created on 2021-02-25 by the reprex package (v1.0.0)

Upvotes: 2

akrun
akrun

Reputation: 887511

We create a sequence column of 1, and then use pivot_wider

library(dplyr)
library(tidyr)
df1 %>% 
  mutate(rn = 1) %>% 
  pivot_wider(names_from = 'names', values_from = c(x, y, z), names_sep = ".") %>%
  select(-rn)

-output

# A tibble: 1 x 6
#    x.A   x.B   y.A   y.B   z.A   z.B
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1     1     2     5     6     7     8

Upvotes: 1

Related Questions