Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting row-values into multiple rows in R dataframe [duplicate]

Tags:

split

dataframe

r

I have an R data frame as follows-

df <- data.frame(
   FDR =  c (0.009, 0.007, 0.007), 
   Probe_ID =  c("1555272_at", "1557203_at", "1557384_at"),
   Gene.Symbol =  c("RSPH10B2///RSPH10B","PABPC1L2B///PABPC1L2A","LOC100506639///ZNF131"),
   Gene.ID = c("728194///222967","645974///340529","100506639///7690"))

df
    FDR   Probe_ID           Gene.Symbol          Gene.ID
1 0.009 1555272_at    RSPH10B2///RSPH10B  728194///222967
2 0.007 1557203_at PABPC1L2B///PABPC1L2A  645974///340529
3 0.007 1557384_at LOC100506639///ZNF131 100506639///7690

I want to split the data frame based on row-values of column df$Gene.symbol, based on pattern ///. The resulted data frame should look like -

FDR     Probe_ID    Gene.symbol     Gene.ID 
0.009   15111_at    RSPH10B2        728194 
0.009   15111_at    RSPH10B         222967 
0.007   15222_at    PABPC1L2B       645974 
0.007   15222_at    PABPC1L2A       340529 
0.007   15333_at    LOC100506639    100506639 
0.007   15333_at    ZNF131          7690

I have tried the following code but it didn't work and produced columns with repetitive elements-

s <- strsplit(gsub("///","",df$Gene.symbol),", ",fixed = TRUE)
res <- data.frame(Id = rep(df$Gene.symbol, lengths(s)), result = unlist(s))
ans <- merge(annotated,res)

Thanks in advance!

like image 949
sp29 Avatar asked Jun 13 '26 04:06

sp29


1 Answers

A solution with dplyr:

library(dplyr)
df %>% 
  separate_rows(Gene.Symbol, Gene.ID, sep = "///")

# A tibble: 6 x 4
    FDR Probe_ID   Gene.Symbol  Gene.ID  
  <dbl> <chr>      <chr>        <chr>    
1 0.009 1555272_at RSPH10B2     728194   
2 0.009 1555272_at RSPH10B      222967   
3 0.007 1557203_at PABPC1L2B    645974   
4 0.007 1557203_at PABPC1L2A    340529   
5 0.007 1557384_at LOC100506639 100506639
6 0.007 1557384_at ZNF131       7690 
like image 140
Dominik S. Meier Avatar answered Jun 17 '26 02:06

Dominik S. Meier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!