Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

For each ID, separate groups into columns and collapse multiple value strings in R

$
0
0

I have a dataframe that looks like this:

in.dat <- data.frame(ID = c("A1", "A1", "A1", "A1", "B1", "B1", "B1", "B1"),
           DB = rep(c("bio", "bio", "func", "loc"), 2),
           val = c("IPR1", "IPR2", "s43", "333-456", 
                   "IPR7", "IPR8", "q87", "566-900"))

  ID   DB     val
1 A1  bio    IPR1
2 A1  bio    IPR2
3 A1 func     s43
4 A1  loc 333-456
5 B1  bio    IPR7
6 B1  bio    IPR8
7 B1 func     q87
8 B1  loc 566-900

I want to turn "DB" into columns and take the string values and collapse by ";"

out.dat <- data.frame(ID = c("A1", "B1"),
                  bio = c("IPR1;IPR2", "IPR7;IPR8"),
                  func = c("s47", "q87"),
                  loc = c("333-456", "566-900"))

> out
  ID       bio func     loc
1 A1 IPR1;IPR2  s47 333-456
2 B1 IPR7;IPR8  q87 566-900

I've played around with pivot_wider and group using dplyr but not quite getting what I want, since a group can have multiple values per ID that I want to collapse into one cell (e.g., "IPR1;IPR2")

Any solution would be appreciated!


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>