split a dataframe up in columns

Viewed 18

I have the following problem: I have a dataframe like the following:

a <- c("h", "b", "c", "h", "b", "c")
b <- c("tnm", "dpm", "cpm", "tnm", "dpm", "cpm")
c <- c("8", "4", "4", "3", "9", "2")
d <- c("a1", "a1", "a1", "a2", "a2", "a2")
data.frame(a, b, c, d) 

which looks like this

  a   b c  d
1 h tnm 8 a1
2 b dpm 4 a1
3 c cpm 4 a1
4 h tnm 3 a2
5 b dpm 9 a2
6 c cpm 2 a2

what I want it to look like is this:

a <- c("h", "b", "c")
b <- c("tnm", "dpm", "cpm")
a1 <- c("8", "4", "4")
a2 <- c("3", "9", "2")
data.frame(a, b, a1, a2)


  a   b a1 a2
1 h tnm  8  3
2 b dpm  4  9
3 c cpm  4  2

would there be a way to do this?

1 Answers

Does this work:

library(dplyr)
library(tidyr)

dt %>% pivot_wider(c(a,b), names_from = d, values_from = c)
# A tibble: 3 × 4
  a     b     a1    a2   
  <chr> <chr> <chr> <chr>
1 h     tnm   8     3    
2 b     dpm   4     9    
3 c     cpm   4     2    
Related